英文:
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 ListItem
s 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 ListItem
s. 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<ListItem>.class
), which fails because it cannot select from a parameterized type
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
得分: 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'll need to use `ParameterizedTypeReference`. If you are _always_ returning a `List<ListItem>`, then you can make it a constant (no need to keep re-instantiating it!):
private static final ParameterizedTypeReference<List<ListItem>> LIST_OF_ITEM =
new ParameterizedTypeReference<List<ListItem>>() {};
Then, in your exchange, use `LIST_OF_ITEM` instead of the class literal `List.class`.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论