How to turn a Java class into one of its subclasses (SocketAddress and InetSocketAddress)

I am trying to get the socket IP connection in string form.

I use a framework that returns a SocketAddressreceived message. How can I convert it to InetSocketAddressor InetAddress?

+3
source share
3 answers

If you are sure that the object is InetSocketAddress, simply produce it:

SocketAddress sockAddr = ...
InetSocketAddress inetAddr = (InetSocketAddress)sockAddr;

You can then call the method getAddress()on inetAddrto associate an object with it InetAddress.

+6
source

You can try casting. In this case, it is downcasting .

InetSocketAddress isa = (InetSocketAddress) socketAddress;

, ClassCastException, , .

instanceof:

if (socketAddress instanceof InetSocketAddress) {
    InetSocketAddress isa = (InetSocketAddress) socketAddress;
    // invoke methods on "isa". This is now safe - no risk of exceptions
}

SocketAddress.

+4

It SocketAddressis actually an abstract class, so you get some subclass of it. Have you tried applying returned SocketAddressto InetSocketAddress?

+1
source

Source: https://habr.com/ru/post/1737829/


All Articles