java - 如何使用反射确定字段类型是否为列表(或任何其他类型的集合)?

标签 java reflection collections

我有这样的东西:

Field [] fields = claz.getDeclaredFields();
 for(Field f : fields){
    f.setAccessible(true);
    if(f.getType().equals(List.class)){
        Method m = f.getType().getMethod("size");
        int length = (Integer)m.invoke(f.get(node));
        System.out.println("length "+ length);
        }
}
它确实有效,但我想知道是否还有其他好的方法,例如适用于所有其他集合(TreeSet、HashSet 等...)的方法,或者唯一的方法是,我必须像我已经拥有的那样检查每种类型吗?

谢谢

最佳答案

Field 对象中,您可以检索类型并将其作为 Collection.class 的方法 isAssignableFrom 的参数传递。

喜欢:

...
boolean isCollection = Collection.class.isAssignableFrom(f.getType())
...

来自文档的方法isAssignableFrom:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

对于Map也应该做同样的事情:

boolean isMap = Map.class.isAssignableFrom(f.getType());

关于java - 如何使用反射确定字段类型是否为列表(或任何其他类型的集合)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196239/

相关文章:

java - Restwebservices 中的正则表达式

c# - 如何使用反射在运行时创建值类型或字符串类型对象

haskell - 我可以在运行时从 Haskell 程序中反射(reflect)消息吗?

forms - Symfony2 表单集合即使 'by_reference' => false 也不调用 addxxx 和 removexxx

c# - 返回两个可枚举之间的差异

c# - IEnumerable<T> 作为返回类型

java - 确定 .class 文件中引用的类

java - EE8 JCache注释CacheResult不起作用

java - 接口(interface)/抽象类

vb.net - 在 vb.net 中使用名称访问属性