【问题标题】:Ambiguous varargs method call compilation error不明确的可变参数方法调用编译错误
【发布时间】:2014-04-09 12:25:51
【问题描述】:
method(1);  // This works -

void method(int... x) { }
void method(int x) { }  // - this method is called

如果我在第二种方法中添加 varargs 参数,则会收到“对方法的引用不明确”的编译错误:

method(1);  // This now fails

void method(int... x) { }
void method(int x, String... y) { }  // adding String... y causes a problem.

作为字符串... y 参数可以保留“空白”,为什么 Java 仍然不选择该方法?谢谢,如果对 SO 有密切匹配的解释,我们深表歉意;我确实找了一个。

【问题讨论】:

  • 您能分享一下您遇到的确切编译器错误吗?
  • @Alexis Leclerc ..\src\pkgs\main\Main.java:1278: 错误:对方法的引用不明确,Main 中的方法 method(int...) 和方法 method(int ,String...) 中的主要匹配方法(1);
  • 我复制粘贴了你的方法,它编译得很好
  • @Gladhus 不可能。你复制了第二个吗?
  • 这里只有一种解释...我的java编译器读懂了我的想法

标签: java variadic-functions


【解决方案1】:

编译器总是选择使用特定的方法。

在第一种情况下,因为参数的数字完全匹配void method(int x),所以它就是被调用的那个。

第二种情况,参数个数不匹配,两种方法都可以调用,造成歧义。

查看JLS - 15.12.2. Compile-Time Step 2: Determine Method Signature了解详情。

【讨论】:

    【解决方案2】:

    参数的数量可以是 0 个或多个。这使得

    void method(int x, String... y){ } 类似于void method(int x){}

    还有

    void method(int... x){}也类似于void method(int x){}

    如果调用method(1),编译器会找到两个适用于该调用的方法并引发和异常。

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多