1

I have data structure that looks more or less like this

class ResponseWrapper<T> {
    T response;

    public ResponseWrapper(T response) {
        this.response = response;
    }
}

And service that handles reading that response from JSON to actual DTO.

public class GenericService<T> {
    public ResponseWrapper<T> read(String json, Class<T> clazz) throws Exception {
        T response = new ObjectMapper().readValue(json, clazz);
        return new ResponseWrapper<>(response);
    }
}

And I can call it like this:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value", SomeData.class)

And what I'm trying to achieve is:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value")

And I'm wondering, is it actually possible? This is obviously not working

  public ResponseWrapper<T> read(String json) throws Exception {
        T response = new ObjectMapper().readValue(json, T.class);
        return new ResponseWrapper<>(response);
    }
Weeedooo
  • 475
  • 6
  • 15
  • This should explain why it doesn't work: [Jackson and generic type reference](//stackoverflow.com/q/6846244) – Tom May 13 '21 at 18:23
  • Does this answer your question? [Jackson and generic type reference](https://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference) – Alex May 13 '21 at 18:38

1 Answers1

0

No. It is not possible.

Java generics work by type erasure ... and that means that the actual class associated with generic type parameter is not available at runtime. If your code needs to know that class, you need to pass a Class object explicitly.

And, yes, T.class is a compilation error.

And, yes, there is no way to get the class of T.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096