This solution wasn't useful for me, therefore this isn't a duplicate, it's a different question.. I'm asking another question because it might render a different solution than the linked post.
I'm trying to create a generic method to use RestTemplate
from Spring, but the type is ignored, and my Object
is not constructed correctly.
Generic Method:
public <T> ResponseEntity<T> restGetRequest(String url, String ... params) {
ParameterizedTypeReference<T> type = new ParameterizedTypeReference<T>() {};
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
return template.exchange(url, HttpMethod.GET, entity, type, params);
}
I'm trying to use this method for any GetRequest
I might use inside my application, making the code smaller.
The Problem:
When trying to retrieve the Object, it's type is not what was expected, and it came as normal JSON
(just a String
).
Retrieving:
String url;
ResponseEntity<MyType> apiResponse = restGetRequest(url);
apiResponse
isn't of type MyType
as I expected it to be. This way, my mapping isn't done correctly.
Is there a way to do this in Java, without creating new classes, nor passing a class as a parameter, nor extending any class? Just using the generic type?