Closed
Description
abccbaandy opened SPR-17539 and commented
When I use
public class MyAdvice implements ResponseBodyAdvice<MyVo>
and my response data is
ResponseEntity<AnotherVo>
ResponseBodyAdvice will throw ClassCastException, because we can't use "supports" to check the type. It make type declare in ResponseBodyAdvice interface useless.
Currently, there is a workaround, use Object
ResponseBodyAdvice<Object>
and check the type in beforeBodyWrite, like this
@Override
public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (!(o instanceof MyVo)) {
return o;
}
// do rest things here
}
but it doesn't look like a best practice.
update:
after study the source, I found there is a class cast before call beforeBodyWrite
RequestResponseBodyAdviceChain
private <T> Object processBody(@Nullable Object body, MethodParameter returnType, MediaType contentType,
Class<? extends HttpMessageConverter<?>> converterType,
ServerHttpRequest request, ServerHttpResponse response) {
for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {
if (advice.supports(returnType, converterType)) {
body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,
contentType, converterType, request, response);
}
}
return body;
}
Can we check body is T before call beforeBodyWrite?
Affects: 5.0.9