ParameterizedTypeReference 的正确使用 [英] Correct usage of ParameterizedTypeReference

查看:27
本文介绍了ParameterizedTypeReference 的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a test I wish to hit an endpoint which returns a list of a type. Currently I have

@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 方法无法解析,因为类型不匹配.

The problem for getForObject method is the ParameterizedTypeReference makes the getForObject method not resolve, as the types do not match up.

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

The problem for the exchange method is incompatible types. Required List but 'exchange' was inferred to ResponseEntity: no instance(s) of type variable(s) exist so that ResponseEntity conforms to List

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

How could I use the ParameterizedTypeReference correctly in this situation to safely return the List type I want?

推荐答案

来自 文档:

对给定的URI模板执行HTTP方法,写入给定的向请求请求实体,并返回响应为响应实体.给定的 ParameterizedTypeReference 用于传递通用类型信息:

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);

因此,在您的情况下,您可以:

So in your case you can:

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

这篇关于ParameterizedTypeReference 的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆