添加toMap和fromMap实现

This commit is contained in:
2024-08-02 09:13:09 +08:00
parent 97cc9002ce
commit 507a6c27e4

View File

@@ -3,6 +3,8 @@ package cn.lihongjie.coal.common;
import cn.lihongjie.coal.base.dto.BaseDto;
import cn.lihongjie.coal.base.entity.BaseEntity;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
@@ -20,7 +22,6 @@ import org.jetbrains.annotations.NotNull;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -41,6 +42,9 @@ public class ReflectUtils {
});
private static final Cache<Tuple2<Class, String>, Optional<Field>> getFieldCache =
CacheBuilder.newBuilder().maximumSize(10000).build();
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String getId(Object o) {
@@ -197,10 +201,17 @@ public class ReflectUtils {
return Map.of();
}
Map<String, Object> map = new HashMap<>();
for (Field e : getAllFieldsList(entity.getClass())) {
map.put(e.getName(), readField(e, entity, true));
return objectMapper.convertValue(entity, new TypeReference<Map<String, Object>>() {});
}
public static <T> T fromMap(Map<String, Object> map, Class<T> cls) {
if (map == null){
return null;
}
return map;
return objectMapper.convertValue(map, cls);
}
}