Search code examples
javaclassparsingreflectioninstanceof

Convert via reflection retrieved object to string (how to iterate over multiple class types?)


I have a getterMethod that returns an type which I retrieve using:

getterMethod.getReturnType()

I need to cast this return value to string. Depending on the type of the returned value, I either need to just use .toString() method on the object, sometimes I need to do more work like using a stringformat for dates etc..

I couldn't help myself but going this way:

Integer i = 1;
if(i.getClass().isInstance(getterMethod.getReturnType())){
    // integer to string
}

But I have lots of possible types, what would be a good and fast approach to resolve this?

Is it possible to use switch case blocks on class-types?


Solution

  • Because of the hierarchic character and inheritance some verbosity will remain.

    Object oriented would be a map.

    Class<?> clazz = getterMethod.getReturnType();
    

    Note that already here inheritance is cruel: a child class may return a derived class of the return type in the super class; and have both getter methods for the same signature.

    You will probably need to handle Class.isPrimitive (Integer.class and int.class) with respect to the value received from the getter.

    Also Class.isArrayType and such.

    But a map of type converters is feasible:

    Map<Class<?>, Function<Object, String>> map;
    
    Function<Object, String> converter;
    do {
         converter = map.get(clazz);
         clazz = clazz.getSuperclass();
    } while (converter == null && clazz != null;
    
    String asText = converter == null
        ? String.valueOf(value)
        : converter.apply(value);