if we have two obejcts a and b of two classes A and B,
public class A{
String prop1;
String prop2;
String prop3;
String prop4;
public A(String prop1, String prop2, String prop3, String prop4) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
this.prop4 = prop4;
}
public A() {
}
//... setters and getters
}
public class B{
String prop2;
String prop3;
public B(String prop2, String prop3) {
this.prop1 = prop1;
this.prop2 = prop2;
this.prop3 = prop3;
this.prop4 = prop4;
}
public B() {
}
}
A a = new A("prop1","prop2","prop3","prop4");
B b = new B();
b.setProp3("p");
How can we copy not null properties from b to a ? in the example above, how we can copy prop3 which is not null and ignore prop2 which is null.
CodePudding user response:
You can use MapStruct.
It's a library that is very easy to use and you can copy all the properties from a class to another.
@Mapper
public interface AToBMapper {
A toB(A a);
B toA(B b);
}
A a = new A("prop1","prop2","prop3","prop4");
B = mapper.toB(a);
This is very useful when you need to copy the properties from a DTO to an Entity.
If you don't want to create a new object but update an existing one, it's also possible as you can see here : MapStruct: How to map to existing target?
More exemple here : https://www.baeldung.com/mapstruct
CodePudding user response:
It would be possible to accomplish this with reflection or a library like BeanUtils but maybe consider using the KISS principle and just write a simple method for it:
public void copyToA(A a, B b) {
if (b.getProp2() != null) a.setProp2(b.getProp2());
if (b.getProp3() != null) a.setProp3(b.getProp3());
}
With BeanUtils you could extend BeanUtilsBean to overwrite copyProperty
and check if the value is null and then just use it like this:
var beanUtilsBean = new YourBeanUtilsBean();
beanUtilsBean.copyProperties(a, b);
For more information check out this answer https://stackoverflow.com/a/3521314/11480721: