2

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 ?

cdxf
  • 5,501
  • 11
  • 50
  • 65

1 Answers1

2

Short answer

It's a Java Generics limitation

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).

Long answer

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.

Example

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.

Also see

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

Impulse The Fox
  • 2,638
  • 2
  • 27
  • 52