【发布时间】:2010-12-12 16:14:23
【问题描述】:
我的课程基本上是另一个课程的副本。
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();
}
}
}
我相信一定有人已经以某种方式做到了这一点
【问题讨论】:
-
是的,或者来自 Apache Jakarta 的 BeanUtils。
标签: java reflection