JAVA后端:复制和转换类常用工具

发布于 2021-11-30  629 次阅读


复制工具类

public class CopyUtils {

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        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 copyProperties(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }
}

转换工具类

public class ConvertUtils {
    /**
     * 获取 null 属性字段
     *
     * @param source source
     * @return 过滤字段
     */
    static String[] getNullPropertyNames(Object source) {
        if (source == null) {
            return null;
        }
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        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);
    }

    /**
     * 类型转换工具类
     * T TO V
     *
     * @param source source
     * @param target 目标
     * @param <T>    source 泛型
     * @param <V>    target 泛型
     * @return V
     */
    public static <T, V> V convert(T source, V target) {
        if (source == null) {
            return null;
        }
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
        return target;
    }

    /**
     * 类型转换工具类
     * List<T> To List<V>
     *
     * @param sourceList sourceList
     * @param tClass     tClass 目标class
     * @param <T>        source 泛型
     * @param <V>        目标class泛型
     * @return List<V></V> 如果sourceList is empty 则返回 null
     */
    public static <T, V> List<V> convertList(List<T> sourceList, Class<V> tClass) {
        if (CollectionUtils.isEmpty(sourceList)) {
            return null;
        }
        List<V> resultList = Lists.newArrayList();
        sourceList.forEach(
                source -> {
                    try {
                        V v = tClass.newInstance();
                        convert(source, v);
                        resultList.add(v);
                    } catch (InstantiationException | IllegalAccessException e) {
                        log.error("实例化对象失败:e = ", e);
                    }
                }
        );
        return resultList;
    }
}

欢迎欢迎~热烈欢迎~