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);
}
}
I think the problem here is that ret
could be any type of Collection: List
, Set
, Map
, Array
, custom class that implements Collection. A List
could be ArrayList
, LinkedList
or any other type of List
implementation. Getting the contents of the List
via reflection would not work. What I suggest is that you support certain collection types as follows:
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)
...
Then you can work with the elements in the array.
Collection implement the Iterable interface, so you can travel through all items in the collection and get them.
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
}
}