无法获得通用的ResponseEntity ,其中T是generics类“SomeClass ”
请帮我一个ResponseEntity
,其中T
本身就是一个generics类型。 正如我现在所看到的,现在spring的RestTemplate不支持这个。 我正在使用Spring MVC 3.1.2版
这是我想要使用的代码:代码:
ResponseEntity<CisResponse> res = this.restTemplate.postForEntity( this.rootURL, myRequestObj, CisResponse.class);
我收到这个错误:
Type mismatch: cannot convert from ResponseEntity to ResponseEntity<CisResponse>
这是明显的错误,但我今天如何解决它?
比我想要获得我的通用响应类型:
CisResponse myResponse= res.getBody(); CisResponseEntity entity = myResponse.getEntityFromResponse();
现在,我使用这个解决方案,使用postForObject()
而不是postForEntity()
:
CisResponse response = this.restTemplate.postForObject( this.rootURL,myRequestObj, CisResponse.class);
这是一个众所周知的问题 。 现在通过引入ParameterizedTypeReference
修复它,这是一个参数化类型,您可以在运行时明确地inheritance它以提供类型信息。 这称为超类型令牌 ,并且可以解决类型擦除问题,因为子类(在本例中是anoniymous)在运行时保留generics超类型的类型参数 。
但是你不能使用postForObject
,因为API只支持exchange()
:
ResponseEntity> res = template.exchange( rootUrl, HttpMethod.POST, null, new ParameterizedTypeReference>() {});
请注意,最后一行演示了超类型标记的概念:您不提供文字CisResponse.class
,而是提供参数化类型ParameterizedTypeReference
的匿名实例化,它在运行时可以提取子类型信息。 您可以将超类型令牌视为实现Foo
黑客
顺便说一句,在Java中你不需要使用this
前缀来访问实例变量:如果你的对象定义了一个url
和template
成员,只需用他们的简单名称来访问它们,而不是像你这样做前缀this.url
和this.template