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. AList
could beArrayList
,LinkedList
or any other type ofList
implementation. Getting the contents of theList
via reflection would not work. What I suggest is that you support certain collection types as follows: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.