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
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.
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);
}
}