获取java.util.List的泛型类型我有;List<String> stringList = new ArrayList<String>();List<Integer> integerList = new ArrayList<Integer>();是否有一种(容易)的方法来检索列表的泛型类型?
3 回答
莫回无
TA贡献1865条经验 获得超7个赞
package test;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<String>(); List<Integer> integerList = new ArrayList<Integer>(); public static void main(String... args) throws Exception { Field stringListField = Test.class.getDeclaredField("stringList"); ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType(); Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0]; System.out.println(stringListClass); // class java.lang.String. Field integerListField = Test.class.getDeclaredField("integerList"); ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType(); Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0]; System.out.println(integerListClass); // class java.lang.Integer. }}
慕村9548890
TA贡献1884条经验 获得超4个赞
class <A extends MyClass> AClass {....}
慕姐8265434
TA贡献1813条经验 获得超2个赞
Type[] types = method.getGenericParameterTypes(); //Now assuming that the first parameter to the method is of type List<Integer>ParameterizedType pType = (ParameterizedType) types[0]; Class<?> clazz = (Class<?>) pType.getActualTypeArguments()[0];System.out.println(clazz); //prints out java.lang.Integer
添加回答
举报
0/150
提交
取消