dimanche 7 juin 2020

Set value of generic type to DTO field

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.





Aucun commentaire:

Enregistrer un commentaire