我有一个类,基本上是另一个类的复制。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我正在做的是在通过Web服务调用之前,将类A中的值放入CopyA中。现在我想创建一个反射方法,基本上是将与类A相同(按名称和类型)的所有字段从类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();
}
}
}
我相信已经有人以某种方式完成了这个。