vendredi 2 octobre 2020

identifying substituted type of Collection using reflection

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?





Aucun commentaire:

Enregistrer un commentaire