如何确定要返回指定类型的列表?

时间:2020-10-16 16:22:58

标签: java httpresponse

我想使用此功能返回ListItem的列表,但是以这种方式进行设置时,我会得到未经检查的分配警告,因为返回的列表未指定包含ListItem 。这会导致构建失败。

  • 在return语句中尝试了强制类型转换,但随后我得到了未经检查的强制类型警告
  • 在声明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();
}

1 个答案:

答案 0 :(得分:1)

您需要使用ParameterizedTypeReference。如果您总是 返回一个List<ListItem>,则可以将其设为常量(无需继续实例化!):

private static final ParameterizedTypeReference<List<ListItem>> LIST_OF_ITEM =
    new ParameterizedTypeReference<List<ListItem>>() {};

然后,在您的交换中,使用LIST_OF_ITEM代替类文字List.class