How to Obtain Generic Type of java.util.List
Consider the following code:
List<String> stringList = new ArrayList<String>(); List<Integer> integerList = new ArrayList<Integer>();
A frequent question arises: is there an effortless method to retrieve the generic type of the list?
Using Reflection
If these lists are fields of a particular class, reflection can be utilized to access their generic types:
import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; public class Test { List<String> stringList = new ArrayList<>(); List<Integer> integerList = new ArrayList<>(); public static void main(String... args) throws Exception { Class<Test> testClass = Test.class; Field stringListField = testClass.getDeclaredField("stringList"); ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType(); Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0]; System.out.println(stringListClass); // class java.lang.String Field integerListField = testClass.getDeclaredField("integerList"); ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType(); Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0]; System.out.println(integerListClass); // class java.lang.Integer } }
Alternative Approaches
The above is the detailed content of How to Get the Generic Type of a Java `List` Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!