Let's say we have an Object A defined like this:
public class ObjectA {
private Attribute a1;
private Attribute a2;
private Attribute a3;
}
For some reason, I need to create a second object B with only the first two attriutes of the Object A :
public class ObjectB {
private Attribute a1;
private Attribute a2;
}
So my question is: what is the best approach to copy an Object A to an Object B ?
I've been copying the attributes by getters and setters one by one but something tells me there must be a better way to do this ! Especially when the object will have a lot of attributes, I have to write lines and lines of code just to copy all of them to the second Object B ...
Thanks a lot :)
EDIT: I've been being alerted by a "possible duplicate of another question" : How do I copy an object in Java?
My question is slightly different in a way that I'm dealing with 2 different objects who just share the same attributes but not totally !
解决方案
To expand on my comment:
Using Dozer it can be as easy as:
Mapper mapper = new DozerBeanMapper();
ObjectA source = new ObjectA();
ObjectB target = mapper.map(source , ObjectB.class);
or if your target class doesn't have a no-arg constructor:
ObjectA source = new ObjectA();
ObjectB target = new ObjectB(/*args*/);
mapper.map(source, target );
From the Documentation (emphasis by me):
After performing the Dozer mapping, the result will be a new instance of the destination object that contains values for all fields that have the same field name as the source object. If any of the mapped attributes are of different data types, the Dozer mapping engine will automatically perform data type conversion.