Retrieving Generic Parameter Types via Java Reflection
In Java, developers may encounter the need to obtain the specific type of a generic parameter at runtime. This question explores how to achieve this common task using Java reflection.
Question:
Is it possible to retrieve the specific type of a generic parameter using Java reflection?
Scenario:
Consider the following code snippet:
public final class Voodoo { public static void chill(List<?> aListWithTypeSpiderMan) { // Here I'd like to get the Class-Object 'SpiderMan' Class typeOfTheList = ???; } public static void main(String... args) { chill(new ArrayList<SpiderMan>()); } }
Answer:
Yes, obtaining the type of a generic parameter with reflection is possible. One approach involves utilizing the following code:
Class<T> persistentClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()) .getActualTypeArguments()[0];
In this code, persistentClass will represent the actual type argument of the generic type, in this case, SpiderMan. However, it is important to note that the underlying reflection mechanisms can be complex, so a thorough understanding of Java generics and reflection is recommended for successful implementation.
The above is the detailed content of Can Java Reflection Retrieve Generic Parameter Types at Runtime?. For more information, please follow other related articles on the PHP Chinese website!