Search code examples
javarestspring-bootgenericsresttemplate

How to define a generic param Class[] and use it on restTemplateBuilder.getForObject()?


I would to create a "generic" get() for all kind of URI and VO in my RestService.

But I dont know how to define (and use it) a parameter to create a generic get(uri, className). I've tried this:

@Service
public class RestService {

    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        // set connection and read timeouts
        this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofSeconds(500))
                .setReadTimeout(Duration.ofSeconds(500))
                .build();
    }

    public Object[] get(String uri, Class[] className){
        return this.restTemplate.getForObject(uri, className);
    }

}

And tried using this way:

String uri = "https://jsonplaceholder.typicode.com/posts";

for (Post post : restService.get(uri, Post.class)) {
    System.out.println(post.getTitle());
}

I got this error:

(argument mismatch; java.lang.Class[] cannot be converted to java.lang.Class<T>))

Edit:

Thanks to @Jonathan Johx, I've changed the params to:

String uri, Class<?> className

But I am not able to iterate

Thanks in advance


Solution

  • you need to test if it's an array and cast:

    String uri = "https://jsonplaceholder.typicode.com/posts";
        Class vo = Post[].class;
    
        Object retorno = restService.get(uri, vo);
        if (retorno.getClass().isArray()) {
            for (int i = 0; i < Array.getLength(retorno); i++) {
                Post post = (Post) Array.get(retorno, i);
                System.out.println(post.getTitle());
            }
        }