java – 变量参数构造函数_may_ conflict,但编译

我有两个编译器编译得很好,但我希望Java抱怨模糊的可能性.

public Foo(int id, Bar bar, String name, String description){
}

public Foo(int id, Bar bar, String... values){
}

是什么赋予了?

Java允许这些方法存在,因为它具有关于如果两者都适用将被调用的规则.具体来说,固定arity方法(没有…)将选择变量arity方法(带…).

JLS, Section 15.12.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.

This guarantees that any calls that were valid in the Java programming
language before Java SE 5.0 are not considered ambiguous as the result
of the introduction of variable arity methods, implicit boxing and/or
unboxing. However, the declaration of a variable arity method (§8.4.1)
can change the method chosen for a given method method invocation
expression, because a variable arity method is treated as a fixed
arity method in the first phase. For example, declaring m(Object…)
in a class which already declares m(Object) causes m(Object) to no
longer be chosen for some invocation expressions (such as m(null)), as
m(Object[]) is more specific.

The second phase (§15.12.2.3) performs overload resolution while
allowing boxing and unboxing, but still precludes the use of variable
arity method invocation. If no applicable method is found during this
phase then processing continues to the third phase.

This ensures that a method is never chosen through variable arity
method invocation if it is applicable through fixed arity method
invocation.

The third phase (§15.12.2.4) allows overloading to be combined with
variable arity methods, boxing, and unboxing.

(强调我的)

示例代码:

class Bar{}

public class Foo{
   public static void main (String [] args){
      Foo main = new Foo(1, new Bar(), "name", "description");
      Foo main2 = new Foo(2, new Bar(), "name");
      Foo main3 = new Foo(3, new Bar(), "name", "description", "otherValues");
      Foo main4 = new Foo(4, new Bar());    
   }

   public Foo(int id, Bar bar, String name, String description) {
      System.out.println("name and description!");
   }

   public Foo(int id, Bar bar, String... values) {
      System.out.println("values!");
   }
}

打印出:

name and description!
values!
values!
values!

…表明如果可以,Java将选择固定的arity方法.

https://stackoverflow.com/questions/19366332/variable-argument-constructor-may-conflict-but-compiles

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 变量参数构造函数_may_ conflict,但编译