首页 > 解决方案 > 检查一个类是否是列表的一个实例

问题描述

我需要获取一个类中可以返回 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.
        }
    }
}

如何获取用于参数化列表的类?

标签: javareflection

解决方案


而不是m.getReturnType(),使用m.getGenericReturnType().

这会给你一个Type. 然后,您需要测试这是否是ParameterizedType: 的实例,如果是,则强制转换并使用getActualTypeArguments().


推荐阅读