请帮我得到一个ResponseEntity<T>
where T
本身就是一个泛型类型。据我所知,Spring RestTemplate 现在不支持这一点。我正在使用 Spring MVC 版本 3.1.2
这是我想使用的代码:
代码:
ResponseEntity<CisResponse<CisResponseEntity>> res =
this.restTemplate.postForEntity(
this.rootURL, myRequestObj, CisResponse.class);
我收到此错误:
Type mismatch: cannot convert from ResponseEntity<CisResponse> to
ResponseEntity<CisResponse<CisResponseEntity>>
这是明显的错误,但今天我该如何解决它呢?
比我确实想要得到我的通用响应类型:
CisResponse<CisResponseEntity> myResponse= res.getBody();
CisResponseEntity entity = myResponse.getEntityFromResponse();
现在,我使用这个解决方案postForObject()
并不是postForEntity()
:
CisResponse<CisResponseEntity> response =
this.restTemplate.postForObject(
this.rootURL,myRequestObj, CisResponse.class);
这是一个已知问题 https://jira.springsource.org/browse/SPR-7023。现在它已经通过引入修复了ParameterizedTypeReference
,这是您明确指定的参数化类型inherit在运行时提供类型信息。这被称为超类型令牌,并且可以解决类型擦除问题,因为子类(在本例中是匿名的)保留泛型超类型的类型参数在运行时。
但是你不能使用postForObject
,因为API只支持exchange() http://static.springsource.org/spring/docs/3.2.0.BUILD/api/org/springframework/web/client/RestTemplate.html:
ResponseEntity<CisResponse<CisResponseEntity>> res = template.exchange(
rootUrl,
HttpMethod.POST,
null,
new ParameterizedTypeReference<CisResponse<CisResponseEntity>>() {});
请注意,最后一行演示了以下想法超类型标记 http://gafter.blogspot.it/2006/12/super-type-tokens.html: 你不提供文字CisResponse.class
,而是参数化类型的匿名实例化ParameterizedTypeReference<T>
,在运行时可以提取子类型信息。您可以将超级类型令牌视为hacks为了实现Foo<Bar<Baz>>.class
顺便说一句,在 Java 中,您不需要对实例变量的访问添加前缀this
:如果你的对象定义了url
and template
成员,只需使用简单的名称即可访问它们,而不是像您一样通过前缀this.url
and this.template
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)