我需要获取类中可以返回列表的所有方法,然后检查所有这些方法的列表类型。当我获得该类型时,我需要检查它是否是特定接口(interface)的实现。
我愿意:
Person person = new Person();
Class c = person.class;
for (Method m: c.getDeclaredMethods()) {
// this gets me all the getters
if (m.getParameterTypes().size() == 0) {
Class<?> returnType = m.getReturnType()
if (returnType.equals(java.util.List.class)) {
// Can get here
// But how to get the class that is used to parameterise the
// list.
}
}
}
如何获取用于参数化列表的类?
最佳答案
使用m.getGenericReturnType()
代替m.getReturnType()
.
这会返回一个类型
。然后您需要测试这是否是 ParameterizedType
的实例:如果是,则使用 getActualTypeArguments()
进行转换并提取类型参数。
关于java - 检查类是否是列表的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55854998/