Getting generic class instance as response

In all my previous post under Spring RestTemplate, I got response as Java objects which were non-generic classes.

Below is an example for your reference

ResponseEntity<Post> postResponseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Post.class);

System.out.println(postResponseEntity.getBody());

When we call “getBody” method, we get an instance of “Post” class.

“Post” is not a generic class.

What if we want to get a generic class as a response.

Below is the main class that shows how we can receives a generic class as a reponse.

Main class

package package10;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.List;

public class Example10 {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://jsonplaceholder.typicode.com/posts";

        ParameterizedTypeReference<List<Post>> typeRef = new ParameterizedTypeReference<List<Post>>() {};

        ResponseEntity<List<Post>> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, typeRef);

        System.out.println(responseEntity.getStatusCode());
        List<Post> posts = responseEntity.getBody();

        for(Post post : posts) {
            System.out.println("--------------------------------------");
            System.out.println(post);
            System.out.println("--------------------------------------");
        }
    }
}

In the above code, I am expecting response of generic type “List” and type parameter being “Post” class i.e., List<Post>.

In the above code, at line 14, I create an instance of “ParameterizedTypeReference” named “typeRef”.

When creating an instance of “ParameterizedTypeReference”, I am mentioning its the type parameter to be the generic information that i am expecting as response.

So in our example, the response we are expecting is “List<Post>”. So i will mention that as type argument to “ParameterizedTypeReference” class when creating its instance.

At line 16, I pass the instance “typeRef” as an argument to “exchange” method, in addition to url, http method type, and request body.

Now once we execute the “exchange” method and get the response, we are getting the body by calling “getBody” method at line 19.

The type returned by “getBody” method will be of “List<Post>” which is what we always wanted.

In the subsequent code, we loop through list and print each “Post” instance to console.

In this way we can get instance of generic class as response body.

Leave a comment