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.
String typeto the type ofFieldthat you are not sure what it can be?