简体   繁体   English

在java.net.DatagramSocket中对构造函数“ super(null)”的模棱两可的调用?

[英]Ambiguous call to constructor “super(null)” in java.net.DatagramSocket?

I am extending the class Java.net.DatagramSocket and giving the subclass its own constructor. 我正在扩展Java.net.DatagramSocket类,并为子类提供自己的构造函数。 The constructor for my new class, UDP_Socket , is as follows 我的新类UDP_Socket的构造函数如下

private UDP_Socket(int port) throws IOException {
    super(null); // Creates an unbound socket.
    super.setReuseAddress(true); // You set reuse before binding.
    super.bind(new InetSocketAddress(port)); // finally, bind
}

The only problem is on the line super(null) , I am getting ambiguous reference to both constructor DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress) . 唯一的问题是在super(null) ,我ambiguous reference to both constructor DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress) I need the super(null) line to create an unbound socket and I believe that I am supposed to set the reuse address socket option before binding. 我需要super(null)行来创建未绑定的套接字,并且我相信应该在绑定之前设置重用地址套接字选项。 How do I fix this error? 如何解决此错误?

The problem is because you call super(null) is valid parameter to both DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress) . 问题是因为您调用super(null)DatagramSocket(DatagramSocketImpl)DatagramSocket(SocketAddress)有效参数。

So, the compiler is confused. 因此,编译器感到困惑。 You can call only one of the constructors. 您只能调用其中一个构造函数。

Use, 采用,

super((DatagramSocketImpl) null);

or, 要么,

super((SocketAddress) null);

depending on which constructor you want to call. 取决于要调用的构造函数。

The error: 错误:

ambiguous reference to both constructor DatagramSocket(DatagramSocketImpl) and DatagramSocket(SocketAddress)

Is telling you that null can reference (DatagramSocketImpl) null or (SocketAddress) null thus making it ambiguous. 告诉您null可以引用(DatagramSocketImpl) null(SocketAddress) null从而使其模棱两可。

You must explicitly call one of the two constructors 您必须显式调用两个构造函数之一

 // super((DatagramSocketImpl) null)
 super((SocketAddress) null)

or have your constructor require that 或者让您的构造函数要求

private UDP_Socket(int port, SocketAddress addr) throws IOException {
    super(addr);

Edit: 编辑:

Code from: Class DatagramSocket 来自以下代码的代码: 类DatagramSocket

 private DatagramSocket getDatagramSocket (int port) {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);
    s.bind(new InetSocketAddress(port));

    return s;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM