如何在RestTemplate中使用泛型参数

如果你想一个请求,这个请求的返回值是泛型的,你可以会执行下面这么一行代码

1
HashMap<String, String> result = restTemplate.getForObject("url", HashMap.class, ...)

现在,Spring有更好的处理方法

1
2
HashMap<String, String> result = restTemplate.exchange("url", HttpMethod.GET, null, new ParameterizedTypeReference<HashMap<String, String>>() {},
...).getBody();

在RestOperations里面有三个可以接收泛型返回值的exchange方法,如下:

1
2
3
4
5
<T> ResponseEntity<T> exchange(String var1, HttpMethod var2, HttpEntity<?> var3, ParameterizedTypeReference<T> var4, Object... var5) throws RestClientException;

<T> ResponseEntity<T> exchange(String var1, HttpMethod var2, HttpEntity<?> var3, ParameterizedTypeReference<T> var4, Map<String, ?> var5) throws RestClientException;

<T> ResponseEntity<T> exchange(URI var1, HttpMethod var2, HttpEntity<?> var3, ParameterizedTypeReference<T> var4) throws RestClientException;

这里ParameterizedTypeReferences<T>的T就是你要的泛型,像上面的代码一样改掉即可。

参考: [1] https://jira.spring.io/browse/SPR-7023