通过反射将所有值从一个类中的字段复制到另一个类 [英] Copy all values from fields in one class to another through reflection
问题描述
我有一个类,它基本上是另一个类的副本。
I have a class which is basically a copy of another class.
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
我正在做的是从类 A中输入值
进入 CopyA
,然后通过网络服务电话发送 CopyA
。现在我想创建一个反射方法,它基本上将所有相同的字段(按名称和类型)从类 A
复制到类 CopyA
。
What I am doing is putting values from class A
into CopyA
before sending CopyA
through a webservice call. Now I would like to create a reflection-method that basically copies all fields that are identical (by name and type) from class A
to class CopyA
.
我该怎么做?
这是我到目前为止所拥有的,但它不是很有效。我认为这里的问题是我正在尝试在我循环的字段上设置一个字段。
This is what I have so far, but it doesn't quite work. I think the problem here is that I am trying to set a field on the field I am looping through.
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();
}
}
}
我是确定必须有某人已经以某种方式完成此操作
I am sure there must be someone that has already done this somehow
推荐答案
如果您不介意使用第三方库, BeanUtils 将使用 copyProperties(Object,Object)轻松处理这个问题/ code>。
If you don't mind using a third party library, BeanUtils from Apache Commons will handle this quite easily, using copyProperties(Object, Object)
.
这篇关于通过反射将所有值从一个类中的字段复制到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!