我有这样的东西:
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/