Spring BeanUtils忽略空值拷贝用法

8,142 阅读1分钟

常用用法

注意:常用BeanUtils类由两个包提供 org.apache.commons.beanutils.BeanUtils、org.springframework.beans.BeanUtils,我们使用的是后者即Spring提供的,如果使用Apache要注意拷贝对象参数位置。

BeanUtils.copyProperties(source, target);

忽略某些字段拷贝

忽略拷贝 id、time字段

BeanUtils.copyProperties(source, target, "id", "time");

忽略空值拷贝

常用于拷贝DTO对象属性到实体类,实体类中部分字段有设置默认值,即可以不将DTO中的空值拷贝过来,保持原有默认值

BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set emptyNames = new HashSet();
        for(java.beans.PropertyDescriptor pd : pds) {
            //check if value of this property is null then add it to the collection
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return (String[]) emptyNames.toArray(result);
    }