[英]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. 我试图以字符串形式获取套接字连接的IP。
I am using a framework, which returns the SocketAddress
of the received message. 我正在使用一个框架,它返回收到的消息的SocketAddress
。 How can i transform it to InetSocketAddress
or InetAddress
? 我怎样才能将其转换为InetSocketAddress
或InetAddress
?
If your certain that the object is an InetSocketAddress
then simply cast it: 如果您确定该对象是InetSocketAddress
那么只需将其InetSocketAddress
:
SocketAddress sockAddr = ...
InetSocketAddress inetAddr = (InetSocketAddress)sockAddr;
You can then call the getAddress()
method on inetAddr
to get the InetAddress
object associated with it. 然后,您可以调用inetAddr
上的getAddress()
方法来获取与之关联的InetAddress
对象。
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. 但是,如果该类不是您所期望的,则可能抛出ClassCastException
。
Checks can be made on this via the instanceof
operator: 可以通过instanceof
运算符对此进行检查:
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
. 可以对SocketAddress
其他子类进行相同的检查。
Actually SocketAddress
is an abstract class, so you receive some subclass of it. 实际上SocketAddress
是一个抽象类,所以你会收到它的一些子类。 Did you try to cast returned SocketAddress
to InetSocketAddress
? 您是否尝试将返回的SocketAddress
InetSocketAddress
为InetSocketAddress
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.