【问题标题】:Groovy resolves ambiguous methods alphabetically by parameter class nameGroovy 按参数类名称的字母顺序解析模棱两可的方法
【发布时间】:2013-09-26 02:51:14
【问题描述】:

Groovy 将通过选择参数类型按字母顺序排列的方法来解决模棱两可的方法调用。在以下示例中,如果 Groovy 调用 MyClass.printIt(null),则将调用采用“A”类型参数的方法。

如果您重构此代码以将 A 类重命名为 C 类,您会发现带有 null myVariable 的调用将解析为采用“B”类型参数的方法,即底部的方法。

    class MyTest {
      public static void main(String[] args) {
        B myVariable = new B()
        new MyClass().printIt(myVariable)
        myVariable = null
        new MyClass().printIt(myVariable)
      }
    }
    class A {}
    class B {}
    class MyClass {
      void printIt(A variable) {
        println "TOP method called"
      }
      void printIt(B variable) {
        println "BOTTOM method called"
      }
    }

上面列出的代码产生以下输出

BOTTOM 方法被调用

调用了 TOP 方法 它调用了带有 B 类型变量的 top 方法

一旦 A 类重命名为 C 类,输出将变为

BOTTOM 方法被调用

BOTTOM 方法被调用

尝试尽可能多的排列,当传入的变量为空时,调用具有最低字母名称的类的方法,即使该变量是为其他类键入的。

groovy --version Groovy 版本:2.0.5 JVM:1.6.0_33 供应商:Sun Microsystems Inc. 操作系统:Windows 7

我的问题是为什么 Groovy 会这样做,这是设计使然还是错误,这种行为是否记录在任何地方?

戴夫

【问题讨论】:

  • 这可能是 groovy 用户邮件列表中的一个

标签: groovy


【解决方案1】:

在我的 groovy (3.0.7) 上,它甚至“更好”:

$ groovy test.groovy
BOTTOM method called
Caught: groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method MyClass#printIt.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [class A]
    [class B]
groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method MyClass#printIt.
Cannot resolve which method to invoke for [null] due to overlapping prototypes between:
    [class A]
    [class B]
    at MyTest.main(test.groovy:6)

【讨论】:

    【解决方案2】:

    无法在 groovy 2.1.6 上重现此问题。也无法在 groovy 2.0.5 上重现这一点。 在这两个用例中,输出都是:

    BOTTOM method called
    TOP method called
    

    当 A 重命名为 C 时输出是

    BOTTOM method called
    TOP method called
    

    Gentoo Linux,JDK 1.7.0_25,

    【讨论】:

    • 感谢您尝试重现此问题,我无法想象可能会有什么不同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多