简体   繁体   English

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

[英]Resolve Java method with omitted varargs parameter

I have the following classes definition: 我有以下类定义:

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

If I do a call like B.foo("hello"); 如果我拨打B.foo("hello");类的电话B.foo("hello"); , then I get a compilation error ,然后出现编译错误

error: non-static method foo(Object) cannot be referenced from a static context 错误:无法从静态上下文引用非静态方法foo(Object)

Of course B.foo("hello", (Object[])null); 当然B.foo("hello", (Object[])null); works just right. 正常工作。 However if I rename the virtual method foo, to foo1 for example, then the compilation error gets gone. 但是,如果我将虚拟方法foo重命名为foo1,那么编译错误就消失了。 It means that first variant of a static method call is still valid, however a compiler tries first to match virtual signature. 这意味着静态方法调用的第一个变体仍然有效,但是编译器会首先尝试匹配虚拟签名。 Can someone provide a right explanation the behavior from the Java language specification document? 有人可以从Java语言规范文档中提供正确的行为解释吗?

The method resolution algorithm is defined in the JLS #15.2.2 . 方法解析算法在JLS#15.2.2中定义。 In substance, methods without varargs have priority over methods that have varargs (emphasis mine): 从本质上讲,不包含可变参数的方法优先于具有可变参数的方法(强调我的方法):

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation . 第一阶段(第15.12.2.2节)执行重载解析, 而不允许装箱或拆箱转换,也不允许使用可变arity方法调用 If no applicable method is found during this phase then processing continues to the second phase. 如果在此阶段未找到适用的方法,则处理将继续进行到第二阶段。

As explained in the JLS, it is done that way " to ensure compatibility with versions of the Java programming language prior to Java SE 5.0 ". 如JLS中所述,这样做是“ 确保与Java SE 5.0之前的Java编程语言版本兼容 ”。

A.foo is NOT static while B.foo is. A.foo不是静态的,而B.foo是静态的。

Calling B.foo("Hello") is an error because inherited A.foo method is NOT static. 调用B.foo("Hello")是错误的,因为继承的A.foo方法不是静态的。 The calls that you say are working probably shows you a warning? 您说的电话可能正在显示警告?

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

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