Unable to get a generic ResponseEntity where T is a generic class “SomeClass”

This was a known issue. Now it’s fixed with the introduction of ParameterizedTypeReference, which is a parameterized type that you explicitely inherit to supply type information at runtime. This is called a super-type token, and works around type erasure because subclasses (anoniymous in this case) keep the type arguments of the generic supertype at runtime.

However you can’t use postForObject, because the API only supports exchange():

ResponseEntity<CisResponse<CisResponseEntity>> res = template.exchange(
        rootUrl,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<CisResponse<CisResponseEntity>>() {});

Note that the last line demonstrates the idea of super type tokens: you don’t supply the literal CisResponse.class, but an anonymous instantiation of the parameterized type ParameterizedTypeReference<T>, which at runtime can be expected to extract subtype information. You can think of super type tokens as hacks for achieving Foo<Bar<Baz>>.class

BTW, in Java you don’t need to prefix access to instance variable with this: if your object defines a url and template members, just access them with their simple name, and not by prefixing like you do this.url and this.template

Leave a Comment