[英]Copy pojo fields to another pojo's setters
Let's say I have class A
with public fields x
and y
.假设我有A
带有公共字段x
和y
类A
。 And let's say I have another pojo class B
but that uses setters and getters, so it has setX() and setY().假设我有另一个 pojo 类B
但它使用 setter 和 getter,所以它有 setX() 和 setY()。
I'd like to use some automatic way to copy from instance of A
to B
and back.我想使用某种自动方式从A
实例复制到B
并返回。
With default settings at least, Dozer's至少在默认设置下,Dozer 的
Mapper mapper = new DozerBeanMapper();
B b = mapper.map(a, B.class);
does not copy the fields correctly.不会正确复制字段。
So is there a simple configuration change that allows me to accomplish the above with Dozer, or another library that would do this for me?那么是否有一个简单的配置更改可以让我使用 Dozer 或其他可以为我完成此操作的库来完成上述操作?
I'd suggest you use:我建议你使用:
http://modelmapper.org/ http://modelmapper.org/
Or take a look at this question:或者看看这个问题:
Copy all values from fields in one class to another through reflection 通过反射将一个类中字段的所有值复制到另一个类中
I'd say that both API's (BeanUtils) and ModelMapper provide one-liners for copy pojos' values to another pojos.我想说的是,API (BeanUtils) 和 ModelMapper 都提供了将 pojos 的值复制到另一个 pojos 的单行程序。 Take a look @ this:看看@这个:
http://modelmapper.org/getting-started/ http://modelmapper.org/getting-started/
Not actually a one-liner but this approach doesn't require any libs.实际上不是单行的,但这种方法不需要任何库。
I was testing it using these classes:我正在使用这些类对其进行测试:
private class A {
public int x;
public String y;
@Override
public String toString() {
return "A [x=" + x + ", y=" + y + "]";
}
}
private class B {
private int x;
private String y;
public int getX() {
return x;
}
public void setX(int x) {
System.out.println("setX");
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
System.out.println("setY");
this.y = y;
}
@Override
public String toString() {
return "B [x=" + x + ", y=" + y + "]";
}
}
To get public field we can use reflection, as for setters it's better to use bean utils:为了获得公共字段,我们可以使用反射,至于 setter 最好使用 bean utils:
public static <X, Y> void copyPublicFields(X donor, Y recipient) throws Exception {
for (Field field : donor.getClass().getFields()) {
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(recipient.getClass()).getPropertyDescriptors()) {
if (field.getName().equals(descriptor.getName())) {
descriptor.getWriteMethod().invoke(recipient, field.get(donor));
break;
}
}
}
}
The test:测试:
final A a = new A();
a.x = 5;
a.y = "10";
System.out.println(a);
final B b = new B();
copyPublicFields(a, b);
System.out.println(b);
And its output is:它的输出是:
A [x=5, y=10]
setX
setY
B [x=5, y=10]
For someone who is still looking for, You could try this using Gson
对于仍在寻找的人,您可以尝试使用Gson
Gson gson = new Gson();
Type type = new TypeToken<YourPOJOClass>(){}.getType();
String data = gson.toJson(workingPOJO);
coppiedPOJO = gson.fromJson(data, type);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.