我有一个类,它基本上是另一个类的副本。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我所做的是在通过 webservice 调用发送 CopyA
之前将类 A
的值放入 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();
}
}
}
我相信一定有人已经这样做了