其他分享
首页 > 其他分享> > springboot中RestTemplate 的getForObject 报错ClassCastException错误

springboot中RestTemplate 的getForObject 报错ClassCastException错误

作者:互联网

1、getForObject的定义如下:

    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
        RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
        HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
        return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
    }

当responseType的泛型T中包含 List 的时候,结果无法转换成 List,这时候便会包ClassCastException 错误

 

2、解决方案

使用 exchange() 方法代替 getForObject

示例:RegulateCommand 为带有 List 的类

RegulateCommand regulateCommandResult = restTemplate.exchange(customConfig.getBaseUrl() + "/sws/regulate_pressure/executing",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<RegulateCommand>() {}).getBody();

 

标签:responseType,springboot,GET,List,RestTemplate,ClassCastException,getForObject,re
来源: https://www.cnblogs.com/lkc9/p/11834803.html