开发者

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

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

I am using a framework, which returns the SocketAddress of the receive开发者_JAVA技巧d message. How can i transform it to InetSocketAddress or InetAddress?


If your certain that the object is an InetSocketAddress then simply cast it:

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

You can then call the getAddress() method on inetAddr to get the InetAddress object associated with it.


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

InetSocketAddress isa = (InetSocketAddress) socketAddress;

However, this may throw ClassCastException if the class isn't really what you expect.

Checks can be made on this via the instanceof operator:

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

The same check can be done for other subclasses of SocketAddress.


Actually SocketAddress is an abstract class, so you receive some subclass of it. Did you try to cast returned SocketAddress to InetSocketAddress?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜