How to copy properties from one Java bean to another?

前端 未结 8 1410
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<?>, Class<?>> map = new HashMap<Class<?>, 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.

    0 讨论(0)
  • 2020-12-17 16:28

    I ran into some problems with Introspector.getBeanInfo not returning all the properties, so I ended up implementing a field copy instead of property copy.

    public static <T> void copyFields(T target, T source) throws Exception{
        Class<?> clazz = source.getClass();
    
        for (Field field : clazz.getFields()) {
            Object value = field.get(source);
            field.set(target, value);
        }
    }
    
    0 讨论(0)
提交回复
热议问题