【问题标题】:How do I make sure I am returning a List of specified type?如何确保返回指定类型的列表?
【发布时间】:2020-10-16 16:22:58
【问题描述】:

我想用这个函数返回一个ListItems 的列表,但是当它以这种方式设置时,我得到一个未经检查的赋值警告,因为返回的列表没有指定包含ListItems。这会导致构建失败。

  • 尝试在 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();
}

【问题讨论】:

标签: java httpresponse


【解决方案1】:

您需要使用ParameterizedTypeReference。如果您总是返回List&lt;ListItem&gt;,那么您可以将其设为常量(无需不断重新实例化它!):

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

然后,在您的交换中,使用 LIST_OF_ITEM 而不是类文字 List.class

【讨论】:

    猜你喜欢
    • 2020-09-20
    • 2016-06-08
    • 2012-02-21
    • 2019-12-22
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多