使用反射从集合类获取对象 [英] using reflection to get objects from collection class
问题描述
我一直在Java中搜索Reflection API。
我想从一个Collection类变量中获取传入对象中的所有对象。
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.
例如
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认为这里的问题是 ret
可以是任何类型的集合: List
, / code>,
映射
,数组
,实现Collection的自定义类。 列表
可以是 ArrayList
, LinkedList
或任何其他类型列表
实现。通过反射获取列表
的内容将不起作用。我建议你是支持某些集合类型如下:
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)
...
使用数组中的元素。
这篇关于使用反射从集合类获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!