gpt4 book ai didi

java - ParameterizedTypeReference 的正确用法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:17 24 4
gpt4 key购买 nike

在测试中,我希望命中一个返回类型列表的端点。目前我有

@Test
public void when_endpoint_is_hit_then_return_list(){
//Given
ParameterizedTypeReference<List<Example>> responseType = new ParameterizedTypeReference<List<Example>>() {};

String targetUrl = "/path/to/hit/" + expectedExample.getParameterOfList();

//When

//This works however highlights an unchecked assignment of List to List<Example>
List<Example> actualExample = restTemplate.getForObject(targetUrl, List.class);

//This does not work
List<Example> actualExample = restTemplate.getForObject(targetUrl, responseType);

//This does not work either
List<Example> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});

//Then
//Assert Results
}

getForObject 方法的问题是 ParameterizedTypeReference 使得 getForObject 方法无法解析,因为类型不匹配。

交换方法的问题是类型不兼容。必需列表,但“交换”被推断为 ResponseEntity:不存在类型变量的实例,因此 ResponseEntity 符合列表

在这种情况下,如何正确使用 ParameterizedTypeReference 来安全地返回我想要的 List 类型?

最佳答案

来自documentation :

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. The given ParameterizedTypeReference is used to pass generic type information:

ParameterizedTypeReference<List<MyBean>> myBean =
new ParameterizedTypeReference<List<MyBean>>() {};

ResponseEntity<List<MyBean>> response =
template.exchange("http://example.com",HttpMethod.GET, null, myBean);

所以在你的情况下你可以:

ResponseEntity<List<Example>> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
List<Example> exampleList = actualExample.getBody();

关于java - ParameterizedTypeReference 的正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51896979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com