Search code examples
javaspringgenericsresttemplate

Java use generic type in ResponseEntity passed as function parameter


I was trying to map response from API to a specific Class table, where Class is passed as an argument. I don't have problems with the same operation in ArrayList.

For example fetchTestPhotos(url, PhotoDto.class) should map response to ResponseEntity<PhotoDto[]>

I tried code below but it didn't work.

public <T> void fetchTestPhotos(String url, Class<T> type) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T[]> response = restTemplate.getForEntity(url, T[].class);

        if (response.getStatusCode().value() != 200) {
            throw new CannotFetchData("Cannot fetch data from " + url);
        }
    }

Solution

  • You actually don't use the parameter type passed to the method which already holds Class<T> which can be PhotoDto.class as you say. Just use this parameter:

    ResponseEntity<T[]> response = restTemplate.getForEntity(url, type);
    

    Moreover, your method returns void type and the response is unused. Change the signature and return the response.

    public <T> ResponseEntity<T> fetchTestPhotos(String url, Class<T> type) {
        ....
        return response;
    }
    

    Finally, if you want to return ResponseEntity<T[]> with generic array, you have also to change the formal parameters. The T and T[] are not interchangeable.

    public <T> ResponseEntity<T[]>  fetchTestPhotos(String url, Class<T[]> type) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T[]> response = restTemplate.getForEntity(url, type);
    
        if (response.getStatusCode().value() != 200) {
            throw new CannotFetchData("Cannot fetch data from " + url);
        }
        return response;
    }