我想使用此功能返回ListItem
的列表,但是以这种方式进行设置时,我会得到未经检查的分配警告,因为返回的列表未指定包含ListItem
。这会导致构建失败。
responseEntity
时尝试指定列表类型,但是随后我还必须指定响应类型参数(List.class
-> List<ListItem>.class
),该方法失败了,因为它无法从中选择参数化类型private static final String GET_LIST_ITEMS= "/listItemsEndpoint";
private final RestTemplate myRestTemplate;
//constructor
public List<ListItem> getListItems() {
headers.add("id", "abc");
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ResponseEntity<List> responseEntity =
myRestTemplate.exchange(GET_LIST_ITEMS, HttpMethod.GET, httpEntity, List.class);
return responseEntity.getBody();
}
答案 0 :(得分:1)
您需要使用ParameterizedTypeReference
。如果您总是 返回一个List<ListItem>
,则可以将其设为常量(无需继续实例化!):
private static final ParameterizedTypeReference<List<ListItem>> LIST_OF_ITEM =
new ParameterizedTypeReference<List<ListItem>>() {};
然后,在您的交换中,使用LIST_OF_ITEM
代替类文字List.class
。