Cannot cast 'org.springframework.http.client.InterceptingClientHttpRequestFactory' to 'org.springframework.http.client.OkHttp3ClientHttpRequestFactory'
由于RestTemplate在自定义初始化时顺序比较早,想在启动后跟进yum或者注解配置修改初始化的值时,直接修改是不能转换成功的,如下:
RestTemplate restTemplate = GlobalContext.getApplicationContext().getBean(RestTemplate.class);
OkHttp3ClientHttpRequestFactory requestFactory = (OkHttp3ClientHttpRequestFactory) restTemplate.getRequestFactory();
requestFactory.setReadTimeout(event.getRpcTimeOut());
这样直接改是会报错:Cannot cast 'org.springframework.http.client.InterceptingClientHttpRequestFactory' to 'org.springframework.http.client.OkHttp3ClientHttpRequestFactory'
解决方案:通过反射设置可访问,可写
ReflectionUtils.makeAccessible
将字段设置可访问,可写。本质就是调用field.setAccessible(true),让非public修饰的字段,可以操作如protected、private修饰的字段。
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) ||
!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
实例代码:
try {
Field field = InterceptingClientHttpRequestFactory.class.getSuperclass().getDeclaredField("requestFactory");
ReflectionUtils.makeAccessible(field);
OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory = (OkHttp3ClientHttpRequestFactory) field.get(factory);
okHttp3ClientHttpRequestFactory.setReadTimeout(event.getRpcTimeOut());
okHttp3ClientHttpRequestFactory.setWriteTimeout(event.getRpcTimeOut());
} catch (Exception e) {
System.out.println("ReflectionUtils.makeAccessible error:" + e.getMessage());
}