Skip to content

Instantly share code, notes, and snippets.

@supernovel
Created August 20, 2019 06:58
Show Gist options
  • Save supernovel/2c00c96a4ef1d7b949b0e532e75f1687 to your computer and use it in GitHub Desktop.
Save supernovel/2c00c96a4ef1d7b949b0e532e75f1687 to your computer and use it in GitHub Desktop.
java merge properties
package com.pixup.admin.common.util;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
public class ObjectUtil {
public static void mergeProperties(
Object source,
Object target
) throws BeansException {
mergeProperties(source, target, null);
}
public static void mergeProperties(
Object source,
Object target,
@Nullable Predicate<Object> filter
) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null) {
PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
if(filter == null || filter.test(value)){
writeMethod.invoke(target, value);
}
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
}
@supernovel
Copy link
Author

ObjectUtil.mergeProperties(source, target, (value) -> {
   return value != null;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment