You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@groovy.apache.org by Kevin <ke...@gmail.com> on 2021/08/17 06:08:17 UTC

Same-named static method invoked instead of instance method

Hi,

I came across interesting behavior while using a third-party API, and I'm
hoping to learn why it happened. The API has a concrete class with two
methods of the same name -- one static, one instance -- as it is an
implementation of two different interfaces. In Groovy (2.4.21), attempting
to invoke the implementation's instance method actually invokes the static
method. Using @CompileStatic changes the call site to invoke the instance
method, which is what I originally expected to happen. Below is a simple
reproducer. In this situation, why does `new Implementation().something()`
result in the AST using `invokeinterface` instead of `invokevirtual`?

```java
// InterfaceWithSomething.java
public interface InterfaceWithSomething {
  String something();
}

// InterfaceWithStaticSomething .java
public interface InterfaceWithStaticSomething {
  static String something() {
    return "Interface's static method";
  }
}

// Implementation.java
public class Implementation implements InterfaceWithSomething,
InterfaceWithStaticSomething {
  @Override
  public String something() {
    return "Implementation's instance method";
  }
}
```

```groovy
// GroovyCode.groovy
class GroovyCode {
  //@groovy.transform.CompileStatic // uncomment to print "Implementation's
instance method"
  static void main(String[] args) {
    def impl = new Implementation()
    println impl.something() // "Interface's static method"
  }
}
```

Thank you.