完全自己实现的工具类,功能简单,比Dozer效率高,且重写get和set方法不会导致属性值丢失,支持map值转实体
使用类
package com.taylor.common.util;
import com.taylor.utils.basetools.BeanMapUtil;
import com.taylor.utils.basetools.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* 类用途:替代Dozer-修改get方法bug
*
* @author taylor
* @version [V1.0, 2020年07月25日]
* @since []
*/
@Slf4j
public class ConvertUtil {
/**
* 转换实体为另一个指定的实体
*
* @param source 源实体,可以是{@code Map<String, Object>} 为NULL时 会抛出NPE
* @param clazz 目标实体 不能为NULL
* @param <T> 泛型
* @return 转换后的结果 转换异常时返回{@code null})
*/
@Nullable
public static <T> T convert(@NonNull Object source, @NonNull Class<T> clazz){
T t = null;
try {
t = clazz.newInstance();
if (source instanceof Map) {
BeanMapUtil.setFieldValue(t,(Map<String, Object>)source);
}else {
BeanUtil.copyBeanProperties(source, t);
}
} catch (Exception e) {
log.error("属性拷贝异常!{}",e.getMessage());
}
return t;
}
/**
* 转换List实体为另一个指定的实体
* source如果为NULL 会使用空集合
* 在目标实体为NULL时 会抛出NPE
*
* @param source 源集合 可以为NULL
* @param clazz 目标实体 不能为NULL
* @param <T> 泛型
* @return 转换后的结果 如果source为空则转为{@link Collections#emptyList()}
*/
@NonNull
public static <T> List<T> convert(@Nullable List<?> source, @NonNull Class<T> clazz) {
return Optional.ofNullable(source)
.orElse(Collections.emptyList())
.stream()
.map(bean -> convert(bean, clazz))
.collect(Collectors.toList());
}
}
属性复制工具实现类
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.taylor.utils.basetools;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
public class BeanUtil extends BeanUtils {
public static void copyBeanProperties(Object source, Object target, String... filters) throws Exception {
List<Field> sourceList = getDeclaredFieldAll(source.getClass(), filters);
List<Field> targetList = getDeclaredFieldAll(target.getClass(), filters);
Iterator var5 = targetList.iterator();
while(var5.hasNext()) {
Field targetField = (Field)var5.next();
if (!Modifier.isFinal(targetField.getModifiers())) {
Field sourceField = searchFields(sourceList, targetField.getName());
if (sourceField != null) {
if (!sourceField.isAccessible()) {
sourceField.setAccessible(true);
}
if (!targetField.isAccessible()) {
targetField.setAccessible(true);
}
Object obj = sourceField.get(source);
if (obj != null) {
try {
targetField.set(target, obj);
} catch (Exception var10) {
var10.printStackTrace();
}</