与固定/可变数量(可变参数)匹配的最具体方法
在 Java 语言规范的第 15.12.2.5 节,讲述了在固定数量的方法和可变数量的方法(即varargs
)两种情况下如何选择最具体的方法。
我在 JLS 中找不到任何关于在两种方法之间进行决定的信息,其中一种方法具有固定数量,另一种方法具有可变数量。例如:
public interface SomeApi {
public String getSomething(String arg); // method 1
public String getSomething(String ... args); // method 2
}
正如人们所期望的那样,编译得很好(由于 Yoni 概述的原因如下)。此调用代码也会编译:
SomeApi api = ...
Object o = api.getSomething("Hello");
如果运行它,则会调用方法#1(即非可变参数方法)。为什么这个调用代码没有歧义?为什么固定数量方法比可变数量方法更具体?有人可以指出我规范的相关部分吗?
In section 15.12.2.5 of the Java Language Specification, it talks about how to choose the most specific method in both cases of methods with fixed arity and methods of variable arity (i.e. varargs
).
What I can't find in the JLS is anything about deciding between two methods where one is of fixed arity and one of variable arity however. For example:
public interface SomeApi {
public String getSomething(String arg); // method 1
public String getSomething(String ... args); // method 2
}
Compiles just fine as one would expect (for reasons outlined by Yoni below). This calling code compiles also:
SomeApi api = ...
Object o = api.getSomething("Hello");
and if you run it, method #1
(i.e. the non-varargs method) is called. Why is this calling-code not ambiguous? Why is the fixed arity method more specific than the variable-arity one? Can someone point me to the relevant bit of the spec?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个方法解析阶段仅考虑固定数量的方法,如果在考虑任何可变参数方法之前找到匹配,则该过程终止。
来自 http://docs.oracle.com /javase/specs/jls/se6/html/expressions.html#15.12.2.2
(我的重点。)
The first method resolution phase considers only fixed arity methods and the process is terminated if a match is found, before any varargs methods are considered.
From http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.2
(My emphasis.)
我无法向您指出规范,但从逻辑上讲,可以
翻译为
毫不含糊地
I can't point you to the spec, but logically,
translates to
with no ambiguity