java 对象序列化处理泛型类型时,核心在于确保泛型参数在运行时依然可被反射获取,通常通过继承具体化的 `parameterizedtype` 来实现。直接序列化泛型类会导致类型擦除,必须使用自定义的 `typereference` 或匿名内部类来保留泛型信息,从而让反序列化框架能正确构建目标对象。

为什么直接序列化泛型类会丢失类型信息
因为 Java 泛型是类型擦除的,运行时无法直接获取泛型参数的具体类型。如果直接传递 `Class

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class TypeReference<T> {
private final Type type;
protected TypeReference() {
// 获取当前类的父类泛型参数
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof ParameterizedType) {
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
} else {
throw new RuntimeException("Missing type information.");
}
}
public Type getType() {
return type;
}
}
// 使用示例:通过匿名内部类保留泛型信息
TypeReference<User> ref = new TypeReference<User>() {};如何在 Jackson 中利用 TypeReference 进行反序列化
Jackson 等主流库支持 `TypeReference` 作为反序列化的目标类型描述符。调用 `readValue` 时传入该引用,库会通过反射解析出泛型参数,并实例化对应的具体类。这解决了 JSON 字符串到复杂泛型对象的映射问题,确保嵌套泛型也能正确处理。
立即学习“Java免费学习笔记(深入)”;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = "[{\"name\":\"Alice\",\"age\":30}]";
// 关键:使用 TypeReference 指定 List<User>
TypeReference<List<User>> typeRef = new TypeReference<List<User>>() {};
List<User> users = mapper.readValue(json, typeRef);
System.out.println(users.get(0).getName()); // 输出: Alice
}
}如何处理泛型字段中的 null 值与默认行为
当泛型字段为 null 时,序列化通常会省略该字段或输出 null,取决于配置。反序列化时,若 JSON 中缺少该字段,框架会根据 Java 默认值(null)填充。对于集合泛型,空数组和 null 需区分处理,避免 `NullPointerException`。建议在 DTO 中使用 `Optional` 或检查非空后再操作。


















