How to parse a String variable into any data type in Java?

Tags: , , , ,



I want to build a method that can convert a String value to a given Field object data type through Java Reflection.

Here is my code:

String value = ...;

Class<? extends MyObject> clazz = getClazz();

Field f = clazz.getDeclaredField("fieldName");
boolean fieldIsAccessible = f.isAccessible();
if (!fieldIsAccessible) {
   f.setAccessible(true);
}

f.getType().cast(value);

if (!fieldIsAccessible) {
    f.setAccessible(false);
}

When I run this code at firs attempt, I receive this exception java.lang.ClassCastException.

I want to convert value to class java.math.BigDecimal.

What is my code missing ?

EDIT: View the solution I came up with.

Answer

Here is the solution I came up with:

public static Object parse(String value, Class<?> clazz) throws NotSupportedException {
    String canonClassName = clazz.getCanonicalName();

    if (canonClassName.equalsIgnoreCase("java.math.BigDecimal")) {
        return new BigDecimal(value);
    }

    // Add other supported classes here ...

    throw new NotSupportedException("The class [" + canonClassName  + "] is not supported.");
}


Source: stackoverflow