属性拷贝如果target属性有值 不覆盖

93 阅读1分钟

bean拷贝忽略指定字段

BeanUtils.copyProperties(defaultCommonRequest, x, getNotNullPropertyNames(x));

获取不为空的属性

    import org.springframework.beans.BeanWrapper;
    import org.springframework.beans.BeanWrapperImpl;
    /**
     * 获取不为空的属性,
     *
     * @param source
     * @return
     */
    private static String[] getNotNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> notEmptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (Objects.nonNull(srcValue)) {
                notEmptyNames.add(pd.getName());
            }

        }
        String[] result = new String[notEmptyNames.size()];
        return notEmptyNames.toArray(result);
    }