maven地址:
使用6.0版本 其他版本使用方法有所不同
<dependency> <groupId>com.github.dozermapper</groupId> <artifactId>dozer-core</artifactId> <version>6.0.0</version> </dependency>
工具类代码,支持过滤null属性不复制的功能。
package com.softium.platform.common.utils; import org.dozer.DozerBeanMapper; import org.dozer.loader.api.BeanMappingBuilder; import org.dozer.loader.api.TypeMappingOptions; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; //import org.dozer.loader.api.TypeMappingOptions.mapEmptyString; public class VoPoConverter { // private static Mapper dozer = DozerBeanMapperBuilder.buildDefault(); private static DozerBeanMapper dozer = new DozerBeanMapper(); /** * 将src对象中的属性值复制到desc对象的同名属性中 * @param src 源 * @param desc 目标 */ public static void copyProperties(Object src, Object desc){ dozer.map(src, desc); } /** * 将src对象中的属性值复制到新建的desc对象的同名属性中 * @param src 源 * @param descClass 目标class * @return */ public static <T> T copyProperties(Object src, Class<T> descClass){ if(src == null ) return null; return (T)dozer.map(src, descClass); } /** * 将srcList中的元素复制到元素类型为descClass的List集合中 * @param srcList 源list * @param descClass 目标list * @return */ public static <T> List<T> copyList(@SuppressWarnings("rawtypes") List srcList, Class<T> descClass){ List<T> descList = new ArrayList<T>(); if (srcList != null){ for (Object obj : srcList){ T t = VoPoConverter.copyProperties(obj, descClass); descList.add(t); } } return descList; } /** * * @Description: copy对象方法,当属性值是null的时候 不赋值,适用于对象修改。 * @param sources 源 * @param destination 目标 * * @version: v1.0.0 * @author: lp * @date: 2019年7月18日 下午3:15:58 * */ public static void copyPropertiesNotNull(final Object sources, final Object destination) { WeakReference weakReference = new WeakReference(new DozerBeanMapper()); DozerBeanMapper mapper = (DozerBeanMapper) weakReference.get(); mapper.addMapping(new BeanMappingBuilder() { @Override protected void configure() { mapping(sources.getClass(), destination.getClass(),TypeMappingOptions.mapNull(false), TypeMappingOptions.mapEmptyString(false)); } }); mapper.map(sources, destination); mapper.destroy(); weakReference.clear(); } }