Skip to content
Advertisement

I can’t understand casting interface to children that don’t have any parents

I am studying lambda and then WebClient Class so I am creating bean of WebClient

JavaScript

I think top codes and bottom codes are the same

JavaScript

I don’t understand this cast situation because HttpMessageWriter is interface and LoggingCodecSupport is class but LoggingCodecSupport doesn’t implement HttpMessageWriter, so I think HttpMessageWriter can’t cast to LoggingCodecSupport

JavaScript

This is the code of HttpMessageWriter

JavaScript

This is the code of LoggingCodecSupport

JavaScript

I tried to test this situation but it makes java.lang.ClassCastException

JavaScript

Help me to understand this thing

and make this code but it makes java.lang.ClassCastException,too

JavaScript

Advertisement

Answer

Assuming you are using the latest Spring, this is because one of the subclasses from LoggingCodecSupport implements the HttpMessageWriter interface.

You can take a look at this class FormHttpMessageWriter

It extends LoggingCodecSupport but implements a HttpMessageWriter interface. That’s why it can be cast without throwing an exception.

The example should be like this

JavaScript

we can assume HttpMessageWriter is the Parent interface, the LoggingCodecSupport is the Child class, and the FormHttpMessageWriter is the Bar class.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement