Correct usage of ParameterizedTypeReference

shirafuno :

In a test I wish to hit an endpoint which returns a list of a type. Currently I have

@Test
public void when_endpoint_is_hit_then_return_list(){
   //Given
   ParameterizedTypeReference<List<Example>> responseType = new ParameterizedTypeReference<List<Example>>() {};

   String targetUrl = "/path/to/hit/" + expectedExample.getParameterOfList();

   //When

   //This works however highlights an unchecked assignment of List to List<Example>
   List<Example> actualExample = restTemplate.getForObject(targetUrl, List.class);

   //This does not work
   List<Example> actualExample = restTemplate.getForObject(targetUrl, responseType);

   //This does not work either
   List<Example> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});

   //Then
   //Assert Results
}

The problem for getForObject method is the ParameterizedTypeReference makes the getForObject method not resolve, as the types do not match up.

The problem for the exchange method is incompatible types. Required List but 'exchange' was inferred to ResponseEntity: no instance(s) of type variable(s) exist so that ResponseEntity conforms to List

How could I use the ParameterizedTypeReference correctly in this situation to safely return the List type I want?

Javad Alimohammadi :

From the documentation:

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. The given ParameterizedTypeReference is used to pass generic type information:

ParameterizedTypeReference<List<MyBean>> myBean =
   new ParameterizedTypeReference<List<MyBean>>() {};

ResponseEntity<List<MyBean>> response =
   template.exchange("http://example.com",HttpMethod.GET, null, myBean);

So in your case you can:

ResponseEntity<List<Example>> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
List<Example> exampleList = actualExample.getBody();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74984&siteId=1