如何将 Java 类变成其子类之一(SocketAddress 和 InetSocketAddress)
我正在尝试以字符串形式获取套接字连接的 IP。
我正在使用一个框架,它返回接收到的消息的SocketAddress
。如何将其转换为 InetSocketAddress
或 InetAddress
?
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 received message. How can i transform it to InetSocketAddress
or InetAddress
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确定该对象是
InetSocketAddress
,则只需对其进行转换:然后您可以在
inetAddr
上调用getAddress()
方法来获取 <与其关联的 code>InetAddress 对象。If your certain that the object is an
InetSocketAddress
then simply cast it:You can then call the
getAddress()
method oninetAddr
to get theInetAddress
object associated with it.您可以尝试投射到它。在本例中,这是向下转型。
但是,如果该类不是您所期望的,则可能会抛出
ClassCastException
。可以通过
instanceof
运算符对此进行检查:可以对
SocketAddress
的其他子类进行相同的检查。You can try casting to it. In this case this is downcasting.
However, this may throw
ClassCastException
if the class isn't really what you expect.Checks can be made on this via the
instanceof
operator:The same check can be done for other subclasses of
SocketAddress
.实际上 SocketAddress 是一个抽象类,因此您会收到它的一些子类。您是否尝试将返回的 SocketAddress 转换为 InetSocketAddress ?
Actually
SocketAddress
is an abstract class, so you receive some subclass of it. Did you try to cast returnedSocketAddress
toInetSocketAddress
?