有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想使用此函数返回一个ListItem列表,但当以这种方式设置时,我会收到一个未检查的分配警告,因为返回的列表未指定包含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();
}

共 (1) 个答案

  1. # 1 楼答案

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

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

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