In Java, would it be possible to implement a function that would take an object as input, and then convert the object to a type that is specified as a parameter?
I'm trying to implement a general-purpose type conversion function for primitive data types, but I don't know exactly where to start:
public static Object convertPrimitiveTypes(Object objectToConvert, String typeToConvertTo){
//Given an object that is a member of a primitive type, convert the object to TypeToConvertTo, and return the converted object
}
For example, convertPrimitiveTypes(true, "String") would return the string "true", and convertPrimitiveTypes("10", "int") would return the integer 10. If the conversion were not well-defined (for example, converting a boolean to an integer), then the method would need to throw an exception, and terminate the program.
I have written this as
public static <T> T convertTo(Object o, Class<T> tClass) {
and it is possible if tedious. If you don't care about efficiency you can can covert to a String and use "Class".valueOf(String) via reflection.
public static void main(String... ignore) {
int i = convertTo("10", int.class);
String s = convertTo(true, String.class);
BigDecimal bd = convertTo(1.2345, BigDecimal.class);
System.out.println("i=" + i + ", s=" + s + ", bd=" + bd);
}
private static final Map<Class, Class> WRAPPER_MAP = new LinkedHashMap<Class, Class>();
static {
WRAPPER_MAP.put(boolean.class, Boolean.class);
WRAPPER_MAP.put(byte.class, Byte.class);
WRAPPER_MAP.put(char.class, Character.class);
WRAPPER_MAP.put(short.class, Short.class);
WRAPPER_MAP.put(int.class, Integer.class);
WRAPPER_MAP.put(float.class, Float.class);
WRAPPER_MAP.put(long.class, Long.class);
WRAPPER_MAP.put(double.class, Double.class);
}
public static <T> T convertTo(Object o, Class<T> tClass) {
if (o == null) return null;
String str = o.toString();
if (tClass == String.class) return (T) str;
Class wClass = WRAPPER_MAP.get(tClass);
if (wClass == null) wClass = tClass;
try {
try {
return (T) wClass.getMethod("valueOf", String.class).invoke(null, str);
} catch (NoSuchMethodException e) {
return (T) wClass.getConstructor(String.class).newInstance(str);
}
} catch (Exception e) {
throw new AssertionError(e);
}
}
prints
i=10, s=true, bd=1.2345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With