如何将 Java 类变成其子类之一(SocketAddress 和 InetSocketAddress)

发布于 2024-08-25 12:36:22 字数 152 浏览 4 评论 0原文

我正在尝试以字符串形式获取套接字连接的 IP。

我正在使用一个框架,它返回接收到的消息的SocketAddress。如何将其转换为 InetSocketAddressInetAddress

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残花月 2024-09-01 12:36:22

如果您确定该对象是 InetSocketAddress,则只需对其进行转换:

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

然后您可以在 inetAddr 上调用 getAddress() 方法来获取 <与其关联的 code>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.

一指流沙 2024-09-01 12:36:22

您可以尝试投射到它。在本例中,这是向下转型

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 的其他子类进行相同的检查。

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.

何时共饮酒 2024-09-01 12:36:22

实际上 SocketAddress 是一个抽象类,因此您会收到它的一些子类。您是否尝试将返回的 SocketAddress 转换为 InetSocketAddress ?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文