001/* 002 * Copyright (C) 2023-present The Prometheus jmx_exporter Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package io.prometheus.jmx.common.configuration; 018 019import io.prometheus.jmx.common.util.Precondition; 020import java.util.function.Function; 021import java.util.function.Supplier; 022 023public class ConvertToString implements Function<Object, String> { 024 025 private final Supplier<? extends RuntimeException> supplier; 026 027 /** 028 * Constructor 029 * 030 * @param supplier supplier 031 */ 032 public ConvertToString(Supplier<? extends RuntimeException> supplier) { 033 Precondition.notNull(supplier); 034 this.supplier = supplier; 035 } 036 037 /** 038 * Method to apply a function 039 * 040 * @param value value 041 * @return the return value 042 */ 043 @Override 044 public String apply(Object value) { 045 if (value == null) { 046 throw new IllegalArgumentException(); 047 } 048 049 try { 050 return (String) value; 051 } catch (Throwable t) { 052 throw supplier.get(); 053 } 054 } 055}