我有一堂课,基本上是另一堂课的副本。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我正在做的是在通过Web服务调用发送之前,将类中的值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();
}
}
}
我敢肯定一定有人已经这样做了