如何确保我返回的是指定类型的列表?

huangapple go评论68阅读模式
英文:

How do I make sure I am returning a List of specified type?

问题

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

- 尝试在返回语句中进行类型转换,但是会得到未经检查的转换警告。
- 尝试在声明 ```responseEntity``` 时指定列表类型,但是我还必须指定响应类型参数(```List.class``` -> ```List<ListItem>.class```),这会失败,因为无法从参数化类型中进行选择。

```java
private static final String GET_LIST_ITEMS= "/listItemsEndpoint";

private final RestTemplate myRestTemplate;

// 构造函数

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();
}
英文:

I would like to return a list of ListItems with this function, but when it is set up this way I get an unchecked assignment warning, because the returned list isnt specified to contain ListItems. This causes the build to fail.

  • Tried casting in the return statement but then I get an unchecked cast warning
  • Tried specifying the list type when declaring the responseEntity, but then I have to also specify the response type parameter (List.class -> List&lt;ListItem&gt;.class), which fails because it cannot select from a parameterized type
private static final String GET_LIST_ITEMS= &quot;/listItemsEndpoint&quot;;

private final RestTemplate myRestTemplate;

//constructor

public List&lt;ListItem&gt; getListItems() {
   
    headers.add(&quot;id&quot;, &quot;abc&quot;);

    HttpEntity&lt;String&gt; httpEntity = new HttpEntity&lt;&gt;(headers);

    ResponseEntity&lt;List&gt; responseEntity =
        myRestTemplate.exchange(GET_LIST_ITEMS, HttpMethod.GET, httpEntity, List.class);


    return responseEntity.getBody();
}

答案1

得分: 1

你需要使用ParameterizedTypeReference。如果您总是返回List<ListItem>,那么您可以将其设置为常量(无需反复实例化!):

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

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

<details>
<summary>英文:</summary>

You&#39;ll need to use `ParameterizedTypeReference`. If you are _always_ returning a `List&lt;ListItem&gt;`, then you can make it a constant (no need to keep re-instantiating it!):

    private static final ParameterizedTypeReference&lt;List&lt;ListItem&gt;&gt; LIST_OF_ITEM =
        new ParameterizedTypeReference&lt;List&lt;ListItem&gt;&gt;() {};

Then, in your exchange, use `LIST_OF_ITEM` instead of the class literal `List.class`.

</details>



huangapple
  • 本文由 发表于 2020年10月17日 00:22:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64392942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定