我一直在搜索有关Java中的Reflection API的几天。我想从传递的对象内的Collection类变量中获取所有对象。
例如
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);
}
}
我觉得这里的问题是,ret
可能是任何类型的收藏:List
,Set
,Map
,Array
,自定义类实现集合。一个List
可能是ArrayList
,LinkedList
或任何其他类型的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)
...
然后,您可以使用数组中的元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句