Get generic type of java.util.List

2018-12-31 05:51发布

I have;

List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();

Is there a (easy) way to retrieve the generic type of the list?

标签: java generics
14条回答
无与为乐者.
2楼-- · 2018-12-31 06:49

You can do the same for method parameters as well:

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
查看更多
登录 后发表回答