package com.zkml.common.util;
import org.dozer.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Description :基于dozer的对象拷贝,仅需要属性名完全相同
* @Author :zhaojun
* @Time :2019-04-22 17:13
*/
public final class CopyUtil {
/**
* 单例 DozerBeanMapper
*/
private final static Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
/**
* 2个实例对象之间的拷贝
*
* @param fromObject 被拷贝源实例对象
* @param toObject 拷贝目标实例对象
*/
public static void copyBean(Object fromObject, Object toObject) {
if (null == fromObject) {
return;
}
try {
mapper.map(fromObject, toObject);
} catch (MappingException e) {
e.printStackTrace();
}
}
/**
* 一个类实例对象拷贝成另一个目标类对象
*
* @param fromObject 被拷贝源实例对象
* @param tClass 拷贝目标类对象
* @return 拷贝目标实例对象
*/
public static <E> E copyBean(Object fromObject, Class<E> tClass) {
if (null == fromObject) {
return null;
}
E obj = null;
try {
obj = mapper.map(fromObject, tClass);
} catch (MappingException e) {
e.printStackTrace();
}
return obj;
}
/**
* 一个类实例对象集合拷贝成另一个目标类对象集合
*
* @param fromObjectList 被拷贝源实例对象集合
* @param tClass 拷贝目标类对象
* @return 拷贝目标实例对象集合
*/
public static <E> List<E> copyBeanList(List<?> fromObjectList, Class<E> tClass) {
List<E> resultList = new ArrayList<E>();
if (null == fromObjectList || fromObjectList.isEmpty()) {
return resultList;
}
for (Object obj : fromObjectList) {
if (null != obj) {
resultList.add(copyBean(obj, tClass));
}
}
return resultList;
}
}