我有一个类,它基本上是另一个类的副本。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我正在做的是将类中的值 A
放入 CopyA
在发送之前 CopyA
通过网络服务调用。现在我想创建一个反射方法,基本上将所有相同的字段(按名称和类型)从类 A
到类 CopyA
。
我怎样才能做到这一点?
这是我到目前为止所拥有的,但它并不完全有效。我认为这里的问题是我试图在我正在循环的字段上设置一个字段。
private <T extends Object, Y extends Object> void copyFields(T from, Y too) {
Class<? extends Object> fromClass = from.getClass();
Field[] fromFields = fromClass.getDeclaredFields();
Class<? extends Object> tooClass = too.getClass();
Field[] tooFields = tooClass.getDeclaredFields();
if (fromFields != null && tooFields != null) {
for (Field tooF : tooFields) {
logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString());
try {
// Check if that fields exists in the other method
Field fromF = fromClass.getDeclaredField(tooF.getName());
if (fromF.getType().equals(tooF.getType())) {
tooF.set(tooF, fromF);
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我相信一定有人已经以某种方式做到了这一点
原文由 Shervin Asgari 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您不介意使用第三方库,Apache Commons 的 BeanUtils 将很容易地处理这个问题,使用
copyProperties(Object, Object)
。