gpt4 book ai didi

java - 使用反射从集合类获取对象

转载 作者:行者123 更新时间:2023-12-04 22:05:59 26 4
gpt4 key购买 nike

我一直在寻找有关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可以是任何类型的Collection:ListSetMapArray,实现Collection的自定义类。 List可以是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)
...


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

关于java - 使用反射从集合类获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18965102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com