问题描述
我有这样一个类:
public class Wrapper< T> {
私人字符串消息;
私人T数据;
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message = message;
}
public T getData(){
return data;
}
public void setData(T data){
this.data = data;
}
}
我使用resttemplate如下:
...
Wrapper< Model> response = restTemplate.getForObject(URL,Wrapper.class,myMap);
Model model = response.getData();
...
然而它会抛出:
ClassCastException
我读到:,但没有帮助。有一些话题与我的问题等有关:和
任何想法?
PS:我的错误是:
java.lang.ClassCastException:java.util.LinkedHashMap不能转换为abcdModel
我认为resttemplate无法理解我的泛型变量,也许它将它接受为Object而不是泛型T.因此它变成了LinkedHashMap。您可以从进行阅读它说,从什么时候解释到:
3.2 M2中引入了ParameterizedTypeReference来解决此问题。
Wrapper< Model> response)= restClient.exchange(loginUrl,
HttpMethod.GET,
null,
new ParameterizedTypeReference< Wrapper< Model>>(){})。getBody();
但是,postForObject / getForObject变体没有引入。
I have a class like that:
public class Wrapper<T> {
private String message;
private T data;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
and I use resttemplate as follows:
...
Wrapper<Model> response = restTemplate.getForObject(URL, Wrapper.class, myMap);
Model model = response.getData();
...
However it throws a:
ClassCastException
I read that: Issue when trying to use Jackson in java but didn't help. There are some topics related to my problem etc.: https://jira.springsource.org/browse/SPR-7002 and https://jira.springsource.org/browse/SPR-7023
Any ideas?
PS: My error is that:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to a.b.c.d.Model
I think resttemplate can not understand my generic variable and maybe it accepts it as an Object instead of generic T. So it becomes a LinkedHashMap. You can read from it here It says that when explaining from what it marshalls to:
ParameterizedTypeReference has been introduced in 3.2 M2 to workaround this issue.
Wrapper<Model> response = restClient.exchange(loginUrl,
HttpMethod.GET,
null,
new ParameterizedTypeReference<Wrapper<Model>>() {}).getBody();
However, the postForObject/getForObject variant was not introduced.
这篇关于泛型与Spring REST模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!