Reputation: 7330
I have a method:
...
import java.lang.reflect.Field;
...
/**
* @param fieldValue - value to update with
* @param fieldClazz - class of value to update with
* @param objectToUpdate - object to update
* @param field - object's field to update
*/
private static void setValueToField(String fieldValue,
Class<?> fieldClazz,
Field field,
Object objectToUpdate)
throws IllegalAccessException {
if (Boolean.class.equals(fieldClazz)) {
field.set(objectToUpdate, Boolean.valueOf(fieldValue));
} else if (String.class.equals(fieldClazz)) {
field.set(objectToUpdate, fieldValue);
} else if (Integer.TYPE.equals(fieldClazz) || Integer.class.equals(fieldClazz)) {
field.set(objectToUpdate, Integer.parseInt(fieldValue));
} else if (Long.TYPE.equals(fieldClazz) || Long.class.equals(fieldClazz)) {
field.set(objectToUpdate, Long.parseLong(fieldValue));
}
// todo continue handling different types?
}
It updates field of objectToUpdate
with fieldValue
represented as String.
Since field
of objectToUpdate
may be of any class, I have to convert String values of fieldValue
to the respective class (which is provided by fieldClazz
). But this approach is messy, especially when it comes to nested objects.
Is there a way, perhaps with something like Jackson, to generify this approach? Like "convert String to provided Class" or something.
Upvotes: 0
Views: 1829
Reputation: 5207
But this approach is messy ...
Messy or not, it depends on how you organize your code. The code you show can be refactored into a clean nice understandable code.
To Jackson: yes, you can use Jackson. But there are some points to keep in mind:
1) You have to provide data in particular format.
2) If you want to use some format that Jackson doesn't understand, you will need to implement your deserializer and to register it, so that Jackson understands when it should be used.
3) Jackson can deserialize some more or less simple structures. There can be more complex cases. For instance, you have a field of type Collection
or List
or your own interface/class with multiple implementations/subclasses, and Jackson can deserialize it by default in some other type than you expect. You would need to provide type information in the string, in many cases also configure Jackson additionally.
There is no magic solution that with a single line of code will deserialize a string to a Java object.
Upvotes: 2