BeanUtils.copyProperties()备忘以及覆盖值问题

BeanUtils.copyProperties()备忘以及覆盖值问题

BeanUtils.copyProperties会进行类型转换; BeanUtils.copyProperties方法简单来说就是将两个字段相同的对象进行属性值的复制。如果 两个对象之间存在名称不相同的属性,则 BeanUtils 不对这些属性进行处理,需要程序手动处理。

这两个类在不同的包下面,而这两个类的copyProperties()方法里面传递的参数赋值是相反的

一、 org.springframework.beans.BeanUtils

a拷贝到b (推荐使用spring的)

a,b为对象
BeanUtils.copyProperties(a, b);

二、org.apache.commons.beanutils.BeanUtils

b拷贝到a

a,b为对象
BeanUtils.copyProperties(a, b);

Demo

import org.springframework.beans.BeanUtils;

public SysUserEnvConf updateConf(SysUserEnvConf userEnvConf) {
    SysUserEnvConf originConf = this.getById(userEnvConf.getId());
    //将 userEnvConf 覆盖拷贝到 originConf ,并排除无值的字段
    BeanUtils.copyProperties(userEnvConf, originConf, getNullPropertyNames(userEnvConf));
    this.updateById(originConf);
    return this.fetchConfDetail();
}

由于BeanUtils.copyProperties()方法会将目标对象(target/dest)全部拷贝到被copy的对象(source/orig)原有数据会被null值覆盖

定义了如下方法


     /**
     * 解决BeanUtils.copyProperties() 的 null值覆盖问题(基本类型的0 0.0)
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for(PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null || Objects.equals(srcValue,0) || Objects.equals(srcValue,0.0)) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

演示

BeanUtils.copyProperties(student3,teacher3,getNullPropertyNames(student3));

图解

file

本方法在引用类型null值覆盖基础上增加了基本类型的情况