2

I have been searching for a few days about the Reflection API in Java. I want to get all the objects from a Collection class variable inside a passed object.

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);
    }
}
4

2 回答 2

6

我认为这里的问题是ret可能是任何类型的 Collection: List, Set, Map, Array, 实现 Collection 的自定义类。AList可以是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)
     ...

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

于 2013-09-23T17:27:42.203 回答
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
    }
}
于 2013-09-23T17:53:24.433 回答