copyProperties 忽略null值字段

在作項目時遇到須要copy兩個對象之間的屬性值,可是有源對象有null值,在使用BeanUtils來copy時null值會覆蓋目標對象的同名字段屬性值,而後採用如下方法找到null值字段,而後忽略:

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));
    }
相關文章
相關標籤/搜索