copy

parent dbada3cf
package com.aps.common.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 生产环境可用的深拷贝工具类
*/
public class ProductionDeepCopyUtil {
private static final ObjectMapper objectMapper = createProductionObjectMapper();
private static ObjectMapper createProductionObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
// 必须的配置
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 可选的安全配置
mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(com.fasterxml.jackson.core.JsonGenerator.Feature.IGNORE_UNKNOWN, true);
return mapper;
}
/**
* 安全的深拷贝(带错误处理)
*/
public static <T> T deepCopy(T source) {
return deepCopy(source, null);
}
/**
* 指定类型的深拷贝
*/
@SuppressWarnings("unchecked")
public static <T> T deepCopy(T source, Class<T> clazz) {
if (source == null) {
return null;
}
try {
Class<?> targetClass = (clazz != null) ? clazz : source.getClass();
String json = objectMapper.writeValueAsString(source);
return (T) objectMapper.readValue(json, targetClass);
} catch (Exception e) {
throw new RuntimeException("深拷贝失败: " + e.getMessage(), e);
}
}
/**
* 带默认值的深拷贝
*/
public static <T> T deepCopy(T source, T defaultValue) {
try {
return deepCopy(source);
} catch (Exception e) {
System.err.println("深拷贝失败,使用默认值: " + e.getMessage());
return defaultValue;
}
}
/**
* 列表深拷贝
*/
public static <T> List<T> deepCopyList(List<T> source) {
if (source == null) {
return new ArrayList<>();
}
try {
String json = objectMapper.writeValueAsString(source);
return objectMapper.readValue(json,
objectMapper.getTypeFactory().constructCollectionType(List.class,
source.isEmpty() ? Object.class : source.get(0).getClass()));
} catch (Exception e) {
throw new RuntimeException("列表深拷贝失败", e);
}
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment