与固定/可变数量(可变参数)匹配的最具体方法

发布于 2024-08-03 04:38:00 字数 709 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瞄了个咪的 2024-08-10 04:38:00

第一个方法解析阶段仅考虑固定数量的方法,如果在考虑任何可变参数方法之前找到匹配,则该过程终止。

来自 http://docs.oracle.com /javase/specs/jls/se6/html/expressions.html#15.12.2.2

15.12.2.2 第 1 阶段:确定适用的匹配数量方法
子类型化

如果没有适用的子类型方法
找到后,搜索适用的
方法继续第 2 阶段
(第 15.12.2.3 节)。 否则,最
选择特定方法(§15.12.2.5)
在适用的方法中
通过子类型。

(我的重点。)

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

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.

(My emphasis.)

落叶缤纷 2024-08-10 04:38:00

我无法向您指出规范,但从逻辑上讲,可以

getSomething(String...args) 

翻译为

getSomething(String[] args)

毫不含糊地

I can't point you to the spec, but logically,

getSomething(String...args) 

translates to

getSomething(String[] args)

with no ambiguity

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文