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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM