资源相关

This commit is contained in:
ZZX9599
2025-09-11 19:28:16 +08:00
parent 627900ac8d
commit eda0bc0999
14 changed files with 1241 additions and 0 deletions

View File

@ -0,0 +1,256 @@
package com.yj.earth.common.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.lang.reflect.*;
import java.util.*;
@Component
public class SourceDataGenerator {
@Resource
private SourceParamsValidator sourceParamsValidator;
private static final ObjectMapper objectMapper;
static {
// 初始化ObjectMapper并配置
objectMapper = new ObjectMapper();
// 允许序列化空对象
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 格式化输出
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
}
/**
* 生成包含完整层级结构的默认JSON
*/
public String generateDefaultJson(String sourceType) throws JsonProcessingException {
// 获取目标类
Class<?> targetClass = sourceParamsValidator.getSourceTypeMap().get(sourceType);
if (targetClass == null) {
throw new IllegalArgumentException("不支持的资源类型: " + sourceType);
}
return generateJsonStructure(targetClass);
}
/**
* 根据类生成JSON结构字符串
* @param clazz 目标类
* @return 完整结构的JSON字符串
*/
public static String generateJsonStructure(Class<?> clazz) throws JsonProcessingException {
Object instance = initializeObject(clazz);
return objectMapper.writeValueAsString(instance);
}
/**
* 递归初始化对象(包括嵌套类、集合、数组)
*/
private static Object initializeObject(Class<?> clazz) {
try {
// 处理数组类型
if (clazz.isArray()) {
return initializeArray(clazz);
}
// 处理基本类型包装类或字符串(直接返回默认值)
if (isPrimitiveOrWrapper(clazz) || clazz.equals(String.class)) {
return getDefaultValue(clazz);
}
// 处理集合接口直接实例化为ArrayList/HashSet等
if (clazz.isInterface()) {
if (List.class.isAssignableFrom(clazz)) {
clazz = ArrayList.class;
} else if (Set.class.isAssignableFrom(clazz)) {
clazz = HashSet.class;
} else if (Map.class.isAssignableFrom(clazz)) {
clazz = HashMap.class;
} else {
// 其他接口默认返回null避免无法实例化
return null;
}
}
// 创建类实例支持static内部类
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true); // 允许访问私有构造函数
Object instance = constructor.newInstance();
// 初始化所有字段
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Class<?> fieldType = field.getType();
// 跳过静态字段(通常不需要序列化静态成员)
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
// 基本类型、包装类、字符串:直接设默认值
if (isPrimitiveOrWrapper(fieldType) || fieldType.equals(String.class)) {
field.set(instance, getDefaultValue(fieldType));
continue;
}
// 处理数组
if (fieldType.isArray()) {
field.set(instance, initializeArray(fieldType));
continue;
}
// 处理集合
if (Collection.class.isAssignableFrom(fieldType)) {
field.set(instance, initializeCollection(field));
continue;
}
// 处理Map
if (Map.class.isAssignableFrom(fieldType)) {
field.set(instance, initializeMap(field));
continue;
}
// 处理嵌套对象包括static内部类
field.set(instance, initializeObject(fieldType));
}
return instance;
} catch (Exception e) {
throw new RuntimeException("初始化对象失败: " + clazz.getName(), e);
}
}
/**
* 初始化数组
*/
private static Object initializeArray(Class<?> arrayType) {
Class<?> componentType = arrayType.getComponentType();
// 创建长度为1的数组
Object array = Array.newInstance(componentType, 1);
// 初始化数组元素(字符串类型会返回空字符串)
try {
Object element = initializeObject(componentType);
Array.set(array, 0, element);
} catch (Exception e) {
// 初始化失败时设置为对应类型的默认值(字符串为""
Array.set(array, 0, getDefaultValue(componentType));
}
return array;
}
/**
* 初始化集合
*/
private static Collection<?> initializeCollection(Field field) {
Class<?> fieldType = field.getType();
Type genericType = field.getGenericType();
Collection<Object> collection;
// 创建具体集合实例
try {
if (fieldType.isInterface()) {
collection = new ArrayList<>();
} else {
collection = (Collection<Object>) fieldType.getDeclaredConstructor().newInstance();
}
} catch (Exception e) {
collection = new ArrayList<>();
}
// 处理泛型元素(字符串类型会添加空字符串)
if (genericType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class) {
Class<?> elementType = (Class<?>) actualTypeArguments[0];
try {
Object element = initializeObject(elementType);
collection.add(element);
} catch (Exception e) {
// 元素初始化失败时添加默认值(字符串为""
collection.add(getDefaultValue(elementType));
}
}
}
return collection;
}
/**
* 初始化Map
*/
private static Map<?, ?> initializeMap(Field field) {
Class<?> fieldType = field.getType();
Type genericType = field.getGenericType();
Map<Object, Object> map;
// 创建具体Map实例
try {
if (fieldType.isInterface()) {
map = new HashMap<>();
} else {
map = (Map<Object, Object>) fieldType.getDeclaredConstructor().newInstance();
}
} catch (Exception e) {
map = new HashMap<>();
}
// 处理泛型键值对value为字符串时设为空字符串
if (genericType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericType).getActualTypeArguments();
if (actualTypeArguments.length == 2) {
try {
// key默认用字符串"key"value按泛型类型设默认值字符串为""
Object key = "key";
Object value = actualTypeArguments[1] instanceof Class
? initializeObject((Class<?>) actualTypeArguments[1])
: getDefaultValue(String.class); // 非Class类型默认空字符串
map.put(key, value);
} catch (Exception e) {
// 初始化失败时value设为对应类型默认值字符串为""
map.put("key", getDefaultValue(actualTypeArguments[1] instanceof Class ? (Class<?>) actualTypeArguments[1] : String.class));
}
}
}
return map;
}
/**
* 判断是否为基本类型或包装类
*/
private static boolean isPrimitiveOrWrapper(Class<?> type) {
return type.isPrimitive()
|| type.equals(Boolean.class)
|| type.equals(Byte.class)
|| type.equals(Short.class)
|| type.equals(Integer.class)
|| type.equals(Long.class)
|| type.equals(Float.class)
|| type.equals(Double.class)
|| type.equals(Character.class);
}
/**
* 获取类型默认值:字符串返回空字符串,其他类型按原有逻辑
*/
private static Object getDefaultValue(Class<?> type) {
if (type.equals(String.class)) {
return "";
}
// 原有逻辑基本类型返回对应默认值boolean=false/数值=0/char='\0'
if (type.isPrimitive()) {
if (type == boolean.class) return false;
if (type == char.class) return '\0';
return 0; // 所有数值类型byte/short/int/long/float/double默认0
}
// 包装类如Integer/Boolean默认返回null保持原有逻辑
return null;
}
}