I have two java objects and I want to merge them into single object. Problem is the two objects does not contain plain primitive type properties(fields) they contain complex
Its pretty easy to do using the org.springframework.beans.BeanUtils class provided by spring. Or the Apache Commons BeanUtils library which I believe Springs version is either based on or is the same as.
public static T combine2Objects(T a, T b) throws InstantiationException, IllegalAccessException {
// would require a noargs constructor for the class, maybe you have a different way to create the result.
T result = (T) a.getClass().newInstance();
BeanUtils.copyProperties(a, result);
BeanUtils.copyProperties(b, result);
return result;
}
if you cant or dont have a noargs constructor maybe you just pass in the result
public static T combine2Objects(T a, T b, T destination) {
BeanUtils.copyProperties(a, destination);
BeanUtils.copyProperties(b, destination);
return destination;
}
If you dont want null properties being copied you can use something like this:
public static void nullAwareBeanCopy(Object dest, Object source) throws IllegalAccessException, InvocationTargetException {
new BeanUtilsBean() {
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if(value != null) {
super.copyProperty(dest, name, value);
}
}
}.copyProperties(dest, source);
}
Nested object solution
Heres a bit more robust solution. It supports nested object copying, objects 1+ level deep will no longer be copied by reference, instead Nested objects will be cloned or their properties be copied individually.
/**
* Copies all properties from sources to destination, does not copy null values and any nested objects will attempted to be
* either cloned or copied into the existing object. This is recursive. Should not cause any infinite recursion.
* @param dest object to copy props into (will mutate)
* @param sources
* @param dest
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static T copyProperties(T dest, Object... sources) throws IllegalAccessException, InvocationTargetException {
// to keep from any chance infinite recursion lets limit each object to 1 instance at a time in the stack
final List
Its kinda quick and dirty but works well. Since it does use recursion and the potential is there for infinite recursion I did place in a safety against.