dozer深拷贝

一、引入maven依赖

maven库 https://mvnrepository.com/artifact/net.sf.dozer/dozer 中选择需要的版本引入
dozer深拷贝_第1张图片

        
            net.sf.dozer
            dozer
            ${dozer.version}
        

选择对应版本

二、工具类

public class BeanUtil {

    private BeanUtil() {
    }

    private static final DozerBeanMapper DOZER = newInstance();

    /**
     * 把source中的值复制到target
     */
    public static void copy(Object source, Object target) {
        if (null == source || null == target) {
            return;
        }
        DOZER.map(source, target);
    }

    /**
     * 把source中的值复制到target
     */
    public static  T copy(Object source, Class target) {
        return null == source || null == target ? null : DOZER.map(source, target);
    }

    /**
     * Copy List集合时可用
     */
    @SuppressWarnings("unchecked")
    public static  List copy(List source) {
        return new ArrayList(source.size()) {
            private static final long serialVersionUID = 1L;

            {
                for (T src : source) {
                    add((T) copy(src, src.getClass()));
                }
            }
        };
    }

    /**
     * Copy List集合时可用[重载]
     */
    public static  List copy(List source, Class target) {
        return new ArrayList(source.size()) {
            private static final long serialVersionUID = 1L;

            {
                for (Object src : source) {
                    add(copy(src, target));
                }
            }
        };
    }

    /**
     * Bean属性输出为Map
     */
    public static Map toMap(Object obj) {

        if (null == obj) {
            return null;
        }
        Map retMap = new LinkedHashMap();

        for (Class clazz = obj.getClass(); !clazz.isAssignableFrom(Object.class); ) {
            for (Field field : clazz.getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    try {
                        field.setAccessible(true);
                        Object val = field.get(obj);
                        if (null != val) {
                            retMap.put(field.getName(), val);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }

        return retMap;
    }

    /**
     * 返回默认实例
     */
    public static DozerBeanMapper newInstance() {
        return new DozerBeanMapper();
    }

}

你可能感兴趣的:(java,dozer)