Java 在作为函数参数传递的 ResponseEntity 中使用通用类型

Java use generic type in ResponseEntity passed as function parameter

我试图将 API 的响应映射到特定的 Class table,其中 Class 作为参数传递。我在 ArrayList 中的相同操作没有问题。

例如 fetchTestPhotos(url, PhotoDto.class) 应将响应映射到 ResponseEntity<PhotoDto[]>

我尝试了下面的代码,但没有成功。

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

您实际上没有使用传递给已经包含 Class<T> 的方法的参数 type,正如您所说,它可以是 PhotoDto.class。只需使用此参数:

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

此外,您的方法 returns void 类型和 response 未使用。更改签名和 return response

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

最后,如果你想return ResponseEntity<T[]> 泛型数组,你也必须改变形参。 TT[] 不可互换。

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