identifying substituted type of Collection using reflection

Viewed 64

I'm writing a little library for automatic generation of test data. It uses reflection to be able to create a randomized instance of any class. I ran in to issues when one of the classes had a field of type List<T>. How do i find out the type of T?

playing around in IntelliJ's "evaluate expression" console, i came up with the following:

 private Class getGenericType(Field field){
        return ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getClass();
    }

which in seemed to work when evaluating in the popup console, but when I put it into the code and run, i get

java.lang.InstantiationException: sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl 
at java.base/java.lang.Class.newInstance(Class.java:571)

any ideas? am I even on the right path?

1 Answers

The first element of the array is already a Class instance so you can do this

 private Class getGenericType(Field field){
    return (Class)((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
 }

Edit: This would only work assuming the generic type is a concrete non-generic type as in List<String>. For more complex cases you will have to check if the type is one that can be instantiated. See comments.

Related