How to copy properties from one Java bean to another?

前端 未结 8 1413
Happy的楠姐
Happy的楠姐 2020-12-17 15:53

I have a simple Java POJO that I would copy properties to another instance of same POJO class.

I know I can do that with BeanUtils.copyProperties() but I would like

8条回答
  •  感情败类
    2020-12-17 16:26

    Hey friends just use my created ReflectionUtil class for copy one bean values to another similar bean. This class will also copy Collections object.

    https://github.com/vijayshegokar/Java/blob/master/Utility/src/common/util/reflection/ReflectionUtil.java

    Note: This bean must have similar variables name with type and have getter and setters for them.

    Now more functionalities are added. You can also copy one entity data to its bean. If one entity has another entity in it then you can pass map option for runtime change of inner entity to its related bean.

    Eg.

    ParentEntity parentEntityObject = getParentDataFromDB();
    Map, Class> map = new HashMap, Class>();
    map.put(InnerBean1.class, InnerEntity1.class);
    map.put(InnerBean2.class, InnerEntity2.class);
    ParentBean parent = ReflectionUtil.copy(ParentBean.class, parentEntityObject, map);
    

    This case is very useful when your Entities contains relationship.

提交回复
热议问题