How to get the generic type of a list in Java?
In Java, it is not possible to directly obtain the generic type of a List because generics are erased during compilation, making it impossible to access the specific generic type information at runtime.
However, it is possible to obtain information about the List generic type using some indirect methods. One common approach is to retrieve it through reflection.
Here is an example code that demonstrates how to use reflection to get the generic type of a List.
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Type genericType = list.getClass().getGenericSuperclass();
if (genericType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
if (actualTypeArguments.length > 0) {
Class<?> genericClass = (Class<?>) actualTypeArguments[0];
System.out.println("List泛型类型为: " + genericClass.getName());
}
}
}
}
In the code above, first we obtain the Class object of List, then we retrieve the generic type information of its superclass. If the generic type is of type ParameterizedType, which means it has actual type parameters, we can use the getActualTypeArguments() method to retrieve an array of actual type parameters. The first element in the array represents the generic type of the List.
It is important to note that the above code assumes that List directly inherits from ArrayList. If List directly implements an interface or inherits from another class, the getGenericSuperclass() method may need to be adjusted. Additionally, if List does not specify a generic type, the length of the array returned by the getActualTypeArguments() method will be 0.