Java 使用反射从集合类获取对象

Java 使用反射从集合类获取对象,java,reflection,collections,Java,Reflection,Collections,几天来,我一直在搜索Java中的反射API。 我想从传递对象内的集合类变量中获取所有对象 例如 public static void getValue引发异常 { 字段[]sourceFields=s.getClass().getDeclaredFields(); 用于(字段sf:sourceFields) { 布尔sa=sf.isAccessible(); sf.setAccessible(真); 字符串targetMethodName=“get”+source.getName().subst

几天来,我一直在搜索Java中的反射API。 我想从传递对象内的集合类变量中获取所有对象

例如

public static void getValue引发异常
{
字段[]sourceFields=s.getClass().getDeclaredFields();
用于(字段sf:sourceFields)
{
布尔sa=sf.isAccessible();
sf.setAccessible(真);
字符串targetMethodName=“get”+source.getName().substring(0,1).toUpperCase()
+(source.getName().substring(1));
方法m=s.getClass().getMethod(targetMethodName,null);
Object ret=m.invoke(s,新对象[]{});
//ret
//检查是否为收集
//如果有的话
//获取其泛型类型
Type Type=f.getGenericType();
//获取其中的所有对象
sf.seta(sa);
}
}

我认为这里的问题是
ret
可以是任何类型的集合:
列表
集合
映射
数组
,实现集合的自定义类。
List
可以是
ArrayList
LinkedList
或任何其他类型的
List
实现。通过反射获取
列表的内容将不起作用。我建议您支持以下特定集合类型:

 Object[] containedValues;
 if (ref instanceof Collection)
     containedValues = ((Collection)ref).toArray();
 else if (ref instanceof Map)
     containedValues = ((Map)ref).values().toArray();
 else if (ref instanceof Object[])
     containedValues = (Object[])ref;
 else if (ref instanceof SomeOtherCollectionTypeISupport)
     ...

然后您可以使用数组中的元素。

集合实现了Iterable接口,因此您可以遍历集合中的所有项并获取它们

Object ref = // something
if (ref instanceof Collection) {
    Iterator items = ((Collection) ref).iterator();
    while (items != null && items.hasNext()) {
        Object item = items.next();
    // Do what you want
    }
}

为什么要使用反射?为什么简单的多态性还不够?就您当前的代码而言,它还不足以表明s可以是一个集合。看看如何约束S的类型。S只是任何对象。我要获取每个字段,包括集合类及其值。所谓“集合”,是指
collection
还是包括数组和
Map
实例?如果包含
Map
,是否需要键和值?您需要提供更明确的要求。
targetMethodName
的值是多少?仅使用
迭代器
toArray
可能是一个更好的主意。此代码是我的最后一个选择,我希望通过尽可能少的硬编码来实现。它确实表示
“来自集合类变量”
(即
实现集合
),因此,这完全有可能是不必要的。你可能是对的,OP在其他任何地方都使用
collection
而不是
collection
,我错过了原来的
C
Object ref = // something
if (ref instanceof Collection) {
    Iterator items = ((Collection) ref).iterator();
    while (items != null && items.hasNext()) {
        Object item = items.next();
    // Do what you want
    }
}