For example: Why not:
Foo result = mapper.readValue<Foo>(jsonStr);
instead of
Foo result = mapper.readValue(jsonStr, Foo.class);
What is the limitation of Java Generics that prevent them from using it ?
For example: Why not:
Foo result = mapper.readValue<Foo>(jsonStr);
instead of
Foo result = mapper.readValue(jsonStr, Foo.class);
What is the limitation of Java Generics that prevent them from using it ?
The limitation is Cannot select from a type variable
. So you can't call T.class
to get the class-object of T which is needed for the next method(s).
Take a look at the implementation
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);
}
They need to pass the valueType
at
_typeFactory.constructType(valueType)
This is not possible with generics.
I've tried the following
private <T> T readValue(String content)
{
return constructType(T.class);
}
private JavaType constructType(Type type)
{
//construct type somehow
}
This doesn't compile. It says Cannot select from a type variable
on T (line 3). Now with the Class argument:
private <T> T readValue(String content, Class<T> clazz)
{
return constructType(clazz);
}
private JavaType constructType(Type type)
{
//construct type somehow
}
This would compile successfully.
How do I get the `.class` attribute from a generic type parameter?