如何使用 java 中的反射找到 Collection(即 Set
或 List
)的大小?
我有类似下面示例的内容,并且想知道如何在使用反射时找到集合的大小。
编辑:
Class<?> clazz = node.getClass();
Field [] fields = clazz.getDeclaredFields();
for(Field field : fields) {
System.out.println("declared fields: "+ field.getType().getCanonicalName());
//getting a generic type of a collection
Type returntype = field.getGenericType();
if (returntype instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) returntype;
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments) {
Class<?> classType = (Class<?>) typeArgument;
System.out.println("typeArgClass = " + classType.getCanonicalName());
}
}
}
最佳答案
假设node
是集合实例。
int size;
try {
size = (Integer) node.getClass().getMethod("size").invoke(node);
} catch (Exception e) {
e.printStackTrace();
}
但是,当您只能调用 node.size()
时,通过反射来执行此操作没有多大意义。
关于java - 如何在java中使用反射查找集合的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11128544/