简体   繁体   中英

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

The error is because the argument mismatch: Class[] cannot be converted to Class<T> . You can fix this, try to handle some generic:

public Object get(URI uri, Class<?> className){
    return restTemplate.getForObject(uri, className);
}

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());
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM