JAVA - How to copy attributes of an object to another object having the same attributes?

一笑奈何 提交于 2019-12-22 05:39:18

问题


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 !


回答1:


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.




回答2:


Try libraries like Dozer or BeanUtils




回答3:


What you need is Object mappers. Try Orika or Dozer. The objects need not be of the same type. While mapping if it finds the attributes of the same name and type, it automatically maps it.

MapperFacade mapper = mapperFactory.getMapperFacade();
UserDTO userDTO = new UserDTO();
userDTO.setName("xyz");
..
User user = mapper.map(userDTO, User.class);

You can also customize if you have to map different attribute names.

MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.classMap(UserDTO.class, User.class)
            .field("name", "username")
            .byDefault().register();
mapper = mapperFactory.getMapperFacade();
...
User user = mapper.map(userDTO, User.class);


来源:https://stackoverflow.com/questions/36196514/java-how-to-copy-attributes-of-an-object-to-another-object-having-the-same-att

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!