将一个javaBean中非空的属性合并到另一个javaBean中
之前将一个 bean 中的属性复制到另一个 bean 中,用的都是 BeanUtils.copyProperties(Object source, Object target);方法;但是这个方法将源bean中空的属性也一起覆盖过来了,就不符合需求了;百度了一下没有找到现成的工具方法;于是就自己写了一个,如果有不对的地方,麻烦评论下,或者私信下我
导包
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
代码
— DemoEntity 为定义的Javabean 也可以写成 Object ;传进来的DemoEntity 中必须要有所有参数的 get 和 set 方法
/**
* 合并 非空的样本属性
* 将 source 中非空的参数值复制到 target 中对应的属性值中
* @param source 来源
* @param target 目标
*/
public static void mergeNotNullProperties(DemoEntity source, DemoEntity target) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());
PropertyDescriptor[] pdes = beanInfo.getPropertyDescriptors();
for(int i = 0; i < pdes.length; i++){
PropertyDescriptor pd = pdes[i] ;
String propertyName = pd.getName();
if (!propertyName.equals("class")) {
PropertyDescriptor sourcePd = new PropertyDescriptor(propertyName, source.getClass()) ;
Method sourceMethod = sourcePd.getReadMethod() ;
Object result = sourceMethod.invoke(source);
if(result != null) {
Method pdWriteMethod = pd.getWriteMethod();
pdWriteMethod.invoke(target, result) ;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
参考博客:
https://blog.csdn.net/iteye_8184/article/details/82613953
https://blog.csdn.net/qq_35340078/article/details/111165080