org.springframework.beans.BeanUtils org.springframework.beans.BeanUtils spring. Apache Commons BeanUtils, , , Springs , .
public static <T> T combine2Objects(T a, T b) throws InstantiationException, IllegalAccessException {
T result = (T) a.getClass().newInstance();
BeanUtils.copyProperties(a, result);
BeanUtils.copyProperties(b, result);
return result;
}
noargs, ,
public static <T> T combine2Objects(T a, T b, T destination) {
BeanUtils.copyProperties(a, destination);
BeanUtils.copyProperties(b, destination);
return destination;
}
, - :
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);
}
. , 1+ , .
public static <T> T copyProperties(T dest, Object... sources) throws IllegalAccessException, InvocationTargetException {
final List<Object> lookingAt = new ArrayList<>();
BeanUtilsBean recursiveBeanUtils = new BeanUtilsBean() {
private boolean isInternal(String name) {
return name.startsWith("java.") || name.startsWith("javax.")
|| name.startsWith("com.sun.") || name.startsWith("javax.")
|| name.startsWith("oracle.");
}
@Override
public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException {
try {
if(lookingAt.stream().anyMatch(o->o == dest)) {
return;
}
lookingAt.add(dest);
super.copyProperties(dest, orig);
} finally {
lookingAt.remove(dest);
}
}
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if (value != null) {
if(!value.getClass().isPrimitive() && !value.getClass().isSynthetic() && !isInternal(value.getClass().getName())) {
try {
Object prop = super.getPropertyUtils().getProperty(dest, name);
if(prop == null) {
super.setProperty(dest, name, super.cloneBean(value));
} else {
copyProperties(prop, value);
}
} catch (NoSuchMethodException e) {
return;
} catch (InstantiationException e) {
throw new RuntimeException("Nested property could not be cloned.", e);
}
} else {
super.copyProperty(dest, name, value);
}
}
}
};
for(Object source : sources) {
recursiveBeanUtils.copyProperties(dest, source);
}
return dest;
}
, . , , .