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

十年热恋 提交于 2019-11-28 07:23:56
Mariusz Jamro

Use BeanUtils:

import org.apache.commons.beanutils.BeanUtils;

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

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.

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.

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.

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