将一个javaBean中非空的属性合并到另一个javaBean中

将一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值