例如: 为什么不:
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/