How to copy properties from a bean to another bean in different class? [duplicate]

安稳与你 提交于 2019-11-27 01:47:46

问题


This question already has an answer here:

  • Copy POJO content from one bean to another 7 answers

I have two java class with same properties names.How Can I copy all the properties to another bean filled with data.I don't want to use the traditional form to copy properties because I have a lot of properties.

Thanks in advance.

1 class

@ManagedBean
@SessionScoped
public class UserManagedBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private String userSessionId;
    private String userId;
    private String name;
    private String adress;
    ......................

2 class

public class UserBean {

    private String userSessionId;
    private String userId;
    private String name;
   ....................

回答1:


Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

UserBean newObject = new UserBean(); 
BeanUtils.copyProperties(newObject, oldObject);



回答2:


Check out the Dozer Framework - its an object to object mapping framework. The idea is that:

  • Usually it will map by convention.
  • You can override this convention with a mapping file.

. . therefore mapping files are as compact as possible. Its useful for many cases, such as mapping a use-case specify service payload on to the reusable core model objects.

When delivering the SpringSource training courses we used to point out this framework very often.

Edit:

These days try MapStruct.




回答3:


If you use Apache's library, BeanUtils, you can do this easily:

http://commons.apache.org/proper/commons-beanutils/

In particular, look at copyProperties(Object, Object)

http://commons.apache.org/proper/commons-beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html#copyProperties(java.lang.Object, java.lang.Object)

Copy property values from the origin bean to the destination bean for all cases where the property names are the same.




回答4:


Use java reflection to set and get property values. There is spring bean property util which does the property value access. I would recommend to you java reflection.



来源:https://stackoverflow.com/questions/19760590/how-to-copy-properties-from-a-bean-to-another-bean-in-different-class

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