gpt4 book ai didi

java - 为什么 Jackson,GSON...不使用泛型而是传递类对象来反序列化对象

转载 作者:行者123 更新时间:2023-11-30 02:13:24 25 4
gpt4 key购买 nike

例如:为什么不:

Foo result = mapper.readValue<Foo>(jsonStr);

而不是

Foo result = mapper.readValue(jsonStr, Foo.class);

Java 泛型有什么限制阻止他们使用它?

最佳答案

简短回答

这是 Java 泛型限制

限制是无法从类型变量中进行选择。因此,您无法调用 T.class 来获取下一个方法所需的 T 的类对象。

长答案

看一下实现

public <T> T readValue(String content, Class<T> valueType)
throws IOException, JsonParseException, JsonMappingException
{
return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueType));
}

public JavaType constructType(Type type) {
return _fromAny(null, type, EMPTY_BINDINGS);
}

他们需要传递valueType

_typeFactory.constructType(valueType)

这对于泛型来说是不可能的。

示例

我尝试过以下方法

private <T> T readValue(String content)
{
return constructType(T.class);
}

private JavaType constructType(Type type)
{
//construct type somehow
}

这不能编译。它显示 T 上的无法从类型变量中进行选择(第 3 行)。现在使用 Class 参数:

private <T> T readValue(String content, Class<T> clazz)
{
return constructType(clazz);
}

private JavaType constructType(Type type)
{
//construct type somehow
}

这将成功编译。

另请参阅

How do I get the `.class` attribute from a generic type parameter?

关于java - 为什么 Jackson,GSON...不使用泛型而是传递类对象来反序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49428088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com