简体   繁体   English

具有固定/可变arity(varargs)匹配的最具体方法

[英]Most specific method with matches of both fixed/variable arity (varargs)

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 (ie varargs ). Java语言规范的第15.12.2.5节中 ,它讨论了如何在具有固定arity的方法和可变arity方法(即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. 我在JLS中找不到的是关于两个方法之间的决定,其中一个是固定的arity,另一个是变量arity 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 ). 按照人们的预期编译就好( 由Yoni概述的原因如下 )。 This calling code compiles also: 这个调用代码也编译:

SomeApi api = ...
Object o = api.getSomething("Hello");

and if you run it, method #1 (ie the non-varargs method) is called. 如果你运行它,则调用method #1 (即非varargs方法)。 Why is this calling-code not ambiguous? 为什么这个调用代码不含糊? Why is the fixed arity method more specific than the variable-arity one? 为什么固定arity方法比变量arity方法更具体? Can someone point me to the relevant bit of the spec? 有人能指出我对规范的相关部分吗?

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. 第一个方法解析阶段仅考虑固定的arity方法,如果在找到任何varargs方法之前找到匹配,则终止该过程。

From http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.2 来自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 15.12.2.2阶段1:确定子类型适用的匹配Arity方法

If no method applicable by subtyping is found, the search for applicable methods continues with phase 2 (§15.12.2.3). 如果找不到子类型适用的方法,则继续第2阶段(第15.12.2.3节)搜索适用的方法。 Otherwise, the most specific method (§15.12.2.5) is chosen among the methods that are applicable by subtyping. 否则,在子类型适用的方法中选择最具体的方法(第15.12.2.5节)。

(My emphasis.) (我的重点。)

I can't point you to the spec, but logically, 我不能指出你的规格,但从逻辑上讲,

getSomething(String...args) 

translates to 翻译成

getSomething(String[] args)

with no ambiguity 毫不含糊

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

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