BeanUtils.copyProperties()拷貝屬性時,忽略空值


把source的屬性值復制給target的相同屬性上,注意:雙方需要復制的屬性要有get、set方法

BeanUtils.copyProperties(source, target, PublicUtils.getNullPropertyNames(source));

/**
     * 獲取所有字段為null的屬性名
     * 用於BeanUtils.copyProperties()拷貝屬性時,忽略空值
     * @param source
     * @return
     */
    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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM