java - 检查一个类是否是列表的一个实例
问题描述
我需要获取一个类中可以返回 List 的所有方法,然后检查所有这些方法是什么类型的 List。当我得到该类型时,我需要检查它是否是特定接口的实现。
我愿意:
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.getReturnType()
,使用m.getGenericReturnType()
.
这会给你一个Type
. 然后,您需要测试这是否是ParameterizedType
: 的实例,如果是,则强制转换并使用getActualTypeArguments()
.
推荐阅读
- selenium - Appium - 无法获取子元素
- python - 有没有办法整合矩阵的每个条目并将解决方案作为另一个矩阵返回?
- android - 如何在我的 android 应用程序上共享来自 whatsapp 的图像和标题
- java - java.lang.IllegalStateException:API 响应后片段未附加到上下文
- reactjs - 使用 Reactjs 的列表中的列表
- angular - 在硬件后退按钮上检查是否存在任何模态并关闭模态
- java - Azure KeyVault:如何添加带有连字符的 Spring 属性作为机密
- laravel - 数据表返回未定义的偏移量,但它在我 dd() 时返回数据
- matplotlib - 在绘图上创建带标签的水平线
- go - 如何在gorm中迁移模型?