<!--dozer-->
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.2.0</version>
</dependency>
/**
* 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
*/
private static Mapper MAPPER = DozerBeanMapperBuilder.buildDefault();
/**
* 基于Dozer转换对象的类型.
*/
public static <T> T map(Object source, Class<T> destinationClass) {
if (source == null) {
return null;
}
return MAPPER.map(source, destinationClass);
}
/**
* 基于Dozer转换Collection中对象的类型.
*/
public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
List<T> destinationList = new ArrayList<>();
for (Object sourceObject : sourceList) {
destinationList.add(MAPPER.map(sourceObject, destinationClass));
}
return destinationList;
}
/**
* 基于Dozer将对象A的值拷贝到对象B中.
*/
public static void map(Object source, Object destination) {
MAPPER.map(source, destination);
}
/**
* @param sourceBean * 被提取的对象bean
* @param targetBean * 用于合并的对象bean
* @return targetBean 合并后的对象
* @Title: merge
* @Description: (因为在使用map方法时遇到有字段没有复制成功 , 所以重写了新方法 , 经试用没问题 。)该方法是用于相同对象不同属性值的合并,如果两个相同对象中同一属性都有值,
* 那么sourceBean中的值会覆盖tagetBean重点的值
* @return: Object
*/
@SuppressWarnings("unused")
public static Object mergeObject(Object sourceBean, Object targetBean) {
Class sourceBeanClass = sourceBean.getClass();
Class targetBeanClass = targetBean.getClass();
Field[] sourceFields = sourceBeanClass.getDeclaredFields();
Field[] targetFields = sourceBeanClass.getDeclaredFields();
for (int i = 0; i < sourceFields.length; i++) {
Field sourceField = sourceFields[i];
Field targetField = targetFields[i];
sourceField.setAccessible(true);
targetField.setAccessible(true);
try {
if (!(sourceField.get(sourceBean) == null) && StringUtils.isNotBlank(sourceField.get(sourceBean).toString())) {
targetField.set(targetBean, sourceField.get(sourceBean));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
return targetBean;
}