public static <A, B> B convert(A instance,
Class<B> targetClass) throws Exception {
B target = (B)targetClass.newInstance();
for (Field targetField : targetClass.getDeclaredFields()) {
targetField.setAccessible(true);
Field field =
instance.getClass().getDeclaredField(targetField.getName());
field.setAccessible(true);
targetField.set(target, field.get(instance));
}
return target;
}
上面是我从论坛获得的代码,当我尝试反映单一类型对象时,它可以工作,但是当我尝试复杂类型时,这意味着内部ClassA
I got ClassB
对象,我得到了java.lang.NoSuchFieldException
。谁能帮我?
您有两个不同的类,很可能具有不同的字段集。
所以如果你的班级A
与你的班级没有相同的字段B
,然后抛出异常。
我建议使用BeanUtils.copyProperties(source, target) http://commons.apache.org/beanutils/v1.8.2/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties%28java.lang.Object,%20java.lang.Object%29 from apache commons-beanutils http://commons.apache.org/beanutils/。您只需自己创建第二个对象,并将其传递给该方法。如果字段不同,它不会抛出异常。
您编写这段代码的最终目标是什么?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)