Home >Java >javaTutorial >Can Reflection Reveal Generic Parameter Types in Java?
Retrieving Generic Parameter Types via Reflection in Java
Query: Can we ascertain the type of a generic parameter using reflection techniques?
Consider the following example:
public final class Voodoo { public static void chill(List<? extends SpiderMan> aListWithTypeSpiderMan) { // Obtain the Class object for 'SpiderMan' Class typeOfTheList = ???; } public static void main(String... args) { chill(new ArrayList<SpiderMan>()); } }
Solution:
A promising approach for extracting the generic parameter type is as follows:
Class<T> persistentClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()) .getActualTypeArguments()[0];
This rather arcane reflection-based incantation appears to furnish us with the desired result, but a more profound understanding of its intricacies eludes me for now.
The above is the detailed content of Can Reflection Reveal Generic Parameter Types in Java?. For more information, please follow other related articles on the PHP Chinese website!