spring的BeanUtil.copyProperties,源对象属性有null覆盖目标对象属性情况解决

解决方法主要有两种:

一、自己写子类

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Author: dyf
 * @Date: 2019/11/7 09:49
 * @Description: 对象属性转换工具类
 */
public class DTOTools extends BeanUtils{

    public static void copyProperties(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null) {
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }


}

二、写一个处理null属性的方法,返回属性为null的set集合

//方式二
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeanUtil.copyProperties方法是一个常用的工具类方法,用于将一个Java对象属性值复制到另一个Java对象。该方法提供了两种常用的用法。 第一种用法是复制所有属性,不包括null属性。使用该用法时,可以直接调用BeanUtil.copyProperties(source, target)方法,将对象属性值复制到目标对象。 第二种用法是复制指定的属性。使用该用法时,需要自定义一个属性过滤器,并在调用BeanUtil.copyProperties(source, target, propertyFilter)方法时传入该过滤器。属性过滤器需要实现PropertyFilter接口,并重写其apply方法,在apply方法判断哪些属性需要复制。 下面是一个示例代码: ```java public class CopyPropertiesExample { public static void main(String[] args) { SourceObject source = new SourceObject(); source.setName("John"); source.setAge(25); source.setEmail("john@example.com"); TargetObject target = new TargetObject(); BeanUtil.copyProperties(source, target, (sourceValue, targetValue, property) -> { // 只复制age和email属性 return "age".equals(property) || "email".equals(property); }); System.out.println(target.getName()); // 输出null System.out.println(target.getAge()); // 输出25 System.out.println(target.getEmail()); // 输出"john@example.com" } } class SourceObject { private String name; private int age; private String email; // 省略getter和setter方法 } class TargetObject { private String name; private int age; private String email; // 省略getter和setter方法 } ``` 在上面的示例,只复制了对象的age和email属性目标对象,name属性没有被复制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值