Java 中哪个重载会被选择为 null?
如果我用 Java 写这行:
JOptionPane.showInputDialog(null, "Write something");
哪个方法会被调用?
showInputDialog(组件父级,对象消息)
showInputDialog(对象消息,对象initialSelectionValue)
我可以测试它。但在其他类似的情况下,我想知道会发生什么。
If I write this line in Java:
JOptionPane.showInputDialog(null, "Write something");
Which method will be called?
showInputDialog(Component parent, Object message)
showInputDialog(Object message, Object initialSelectionValue)
I can test it. But in other cases similar to this, I want to know what happens.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将调用最具体的方法 - 在这种情况下,
这通常位于"确定方法签名" 规范 (15.12.2) 中重载解析的步骤,特别是 “选择最具体的方法”。
在不深入细节的情况下(您可以在规范中阅读这些细节),简介给出了很好的总结:
The most specific method will be called - in this case
This generally comes under the "Determine Method Signature" step of overload resolution in the spec (15.12.2), and in particular "Choosing the Most Specific Method".
Without getting into the details (which you can read just as well in the spec as here), the introduction gives a good summary:
在您的特定情况下,将调用更具体的方法。但一般来说,在某些情况下方法签名可能不明确。请考虑以下情况:
在这种情况下,编译器无法在采用 Integer 的方法和采用 String 的方法之间做出决定。当我尝试编译它时,我得到
In your particular case the more specific method will be called. In general, though, there are some cases where the method signature can be ambiguous. Consider the following:
In this case, the compiler can't decide between the method that takes an Integer and the method that takes a String. When I try to compile that, I get
<罢工>都不是。您将收到编译器错误,要求您澄清要调用什么方法。您可以通过显式转换第一个参数来做到这一点:
或
更新 我应该知道 - 永远不要怀疑 Jon Skeet。我上面提到的问题仅在无法确定哪种方法更具体时才会出现。这是一个测试用例:
上面将给出编译器错误。
Neither. You'll get a compiler error asking you to clarify what method you want to call. You can do so by explicitly casting the first argument:or
Update I should have known - never doubt Jon Skeet. The problem I've referred to above only occurs when it's impossible to determine which method is more specific. Here's a test case:
The above will give a compiler error.