samedi 29 avril 2017

Retrieve the classes used within an instance of a Generic Type using Reflection

Suppose to have a type Pair<K,V> declared in your package. Given an object instance of:

 Pair<Integer, Integer> obj = new Pair<>(1,23);

I want to retrieve the type arguments Integer and Integer to which K and V are respectively associated. By the way, it seems to be that using Java standard reflection I cannot access to the actual class with the instances within Java.

 TypeVariable<? extends Class<?>>[] parameters = obj.getClass().getTypeParameters();

I did not manage to extract such desired information using such parameters. I start to wonder, maybe the type information is kept only at compile time, while at run time the actual type parameter information is removed.





Aucun commentaire:

Enregistrer un commentaire