你如何获得带有reflection的List ?
我得到一个方法,并检查method.getParameterTypes()[0]
,这是一个java.util.List
。 但我想弄清楚包含类型是什么,例如,如果它是java.util.List
我想弄清楚它应该包含字符串。
我该怎么做呢?
谢谢!
Type listType = method.getGenericParameterTypes()[0]; if (listType instanceof ParameterizedType) { Type elementType = ((ParameterizedType) listType).getActualTypeArguments()[0]; }
请注意,元素类型不必是像String
这样的实际Class
– 它可以是类型变量,通配类型等。
您可以在此处和此处阅读有关从reflection项中抓取generics信息的更多信息。
这很简单:你做不到。 在编译时,Java会擦除generics类型(请参阅类型擦除 )。
你可以在这里和这里看到有关GetGenericType
更多信息(老实说,我不知道),但它似乎相当有限。
我有同样的问题,我做了如下
在这里:你的类初始化为clazz(例如 – Company.Class)和你的Collection as
List
companyEmployee
String collectionType
– 列表
String collectionContent
– Employee
Method[] methodList = clazz.getDeclaredMethods(); Method classMethod = methodList[0]; String[] collection= classMethod.getReturnType().toString().split("\\."); String collectionType = collection[collection.length - 1] String collectionContent = classMethod.getGenericReturnType().getTypeName().split("<")[1].split(">")[0]