gpt4 book ai didi

java - 使用省略的 varargs 参数解析 Java 方法

转载 作者:行者123 更新时间:2023-11-29 03:02:34 25 4
gpt4 key购买 nike

我有以下类定义:

class A {
String foo(Object par) {
return par.toString();
}
}
class B extends A {
static String foo(String par, Object ... pars) {
return par.toString();
}
}

如果我调用 B.foo("hello"); ,那么我会得到一个编译错误

错误:无法从静态上下文中引用非静态方法 foo(Object)

当然 B.foo("hello", (Object[])null); 工作得恰到好处。但是,如果我将虚方法 foo 重命名为 foo1,那么编译错误就会消失。这意味着静态方法调用的第一个变体仍然有效,但是编译器首先尝试匹配虚拟签名。有人可以对 Java 语言规范文档中的行为提供正确的解释吗?

最佳答案

方法解析算法在JLS #15.2.2中定义.实际上,没有可变参数的方法优先于有可变参数的方法(强调我的):

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

如 JLS 中所述,这样做是为了“确保与 Java SE 5.0 之前的 Java 编程语言版本的兼容性”。

关于java - 使用省略的 varargs 参数解析 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33933533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com