在section 15.12.2.5 of the Java Language Specification ,它讨论了如何在具有固定元数的方法和可变元数的方法(即 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
(即非可变参数方法)将被调用。为什么这个调用代码没有歧义?为什么固定元数方法比可变元数方法更具体?有人可以指出规范的相关部分吗?
最佳答案
第一个方法解析阶段仅考虑固定数量的方法,如果找到匹配项,则在考虑任何可变参数方法之前终止该过程。
来自 http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.2
15.12.2.2 Phase 1: Identify Matching Arity Methods Applicable by Subtyping
If no method applicable by subtyping is found, the search for applicable methods continues with phase 2 (§15.12.2.3). Otherwise, the most specific method (§15.12.2.5) is chosen among the methods that are applicable by subtyping.
(我的重点。)
关于java - 匹配固定/可变元数(可变参数)的最具体方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1321657/