BeanUtils.copyProperties在拷贝属性时忽略空值

最近在写一个小玩意的时候,须要在两个对象之间拷贝属性java

使用的是app

BeanUtils.copyPropertiesspa

但是,有一个问题code

就是当src对象的键值为Null时对象

就会把target对象的对应键值覆盖成空了blog

这不科学ip

因此找了下面的这个方式来解决get

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));
    }

我想见新桓结衣

相关文章
相关标签/搜索