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

时间:2013-09-23 17:15:07

标签: java reflection collections

我一直在搜索Java中的Reflection API几天。 我想从传递的对象中获取Collection类变量中的所有对象。

E.g。

public static <S>void getValue(S s)throws Exception
{
    Field[] sourceFields = s.getClass().getDeclaredFields();
    for (Field sf : sourceFields) 
    {
        boolean sa = sf.isAccessible();
        sf.setAccessible(true);

        String targetMethodName = "get" + source.getName().substring(0, 1).toUpperCase()
                + (source.getName().substring(1));
        Method m = s.getClass().getMethod(targetMethodName, null) ;
        Object ret = m.invoke(s, new Object[] {});

        //ret 
        //check whether it is collection
        //if yes
        //get its generic type
        Type type = f.getGenericType();

        //get all the objects inside it

        sf.setAccessible(sa);
    }
}

2 个答案:

答案 0 :(得分:5)

Collection实现了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
    }
}

答案 1 :(得分:4)

我认为这里的问题是ret可以是任何类型的集合:ListSetMapArray,实现的自定义类采集。 List可以是ArrayListLinkedList或任何其他类型的List实施。通过反射获取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)
     ...

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

相关问题