Catalina
Catalina

Reputation: 693

Trying to generify method with ResponseEntity and RestTemplate

I have the method below where I am trying to make it more generic so that the method can take any type I want:

public PersonResult getAllPersons (PersonMeta meta) {
    final String uri = addParams(getURI(), meta);
    final ResponseEntity<PersonResult> response = this.restTemplate.getForEntity(uri, PersonResult .class);
    if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
        throw new HttpClientErrorException("There are no persons available.");
    }
    return response.getBody();
}

My try: but returns NullPointerException at response position

public <T, R> R getAllPersons (T meta) {
    final String uri = addParams(getURI(), meta);
    final ResponseEntity<R> response = (ResponseEntity<R>) this.restTemplate.getForEntity(uri, Object.class);
    if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
        throw new HttpClientErrorException("There are no persons available.");
    }
    return response.getBody();
}

Upvotes: 1

Views: 333

Answers (1)

samabcde
samabcde

Reputation: 8114

Pass the result class as a parameter also.

public <T, R> R getAllPersons(T meta, Class<R> resultClass) {
    final String uri = addParams(getURI(), meta);
    final ResponseEntity<R> response = this.restTemplate.getForEntity(uri, resultClass);
    if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) {
        throw new HttpClientErrorException("There are no persons available.");
    }
    return response.getBody();
}

Upvotes: 2

Related Questions