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 parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.
A parsing operation converts a string that represents a . NET base type into that base type. For example, a parsing operation is used to convert a string to a floating-point number or to a date-and-time value. The method most commonly used to perform a parsing operation is the Parse method.
In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.
You could make this work for classes that have a string constructor like this:
f.getType().getConstructor( String.class ).newInstance( value );
In Java, there is no universal method for converting a String into an instance of an arbitrary class. Many classes simply don't support such a conversion. And there's no standard interface for those that do support it.
Your best bet is to look for a constructor that accepts a String as its sole argument. Of course, not every class provides such a constructor, and there's no guarantee that the semantics would be what you'd expect.
There is a Github project (MIT Licensed) called type-parser which does converting a string value to the desired data type
Here is the project description from GitHub
This is a light weight library that does nothing but parse a string to a given type. Supports all applicable java classes, such as Integer, File, Enum, Float etc., including generic Collection types/interfaces such as List, Set, Map, arrays and even custom made types. Also possible to register your own parsers.
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