Search code examples
groovymetaclassinterceptionmethod-invocation

Groovy runtime method interception


I'm playing with Groovy and I wonder, why doesn't this piece of code works?

package test

interface A {
    void myMethod()
}

class B implements A {
    void myMethod() {
        println "No catch"
    }
}

B.metaClass.myMethod = {
    println "Catch!"
}

(new B()).myMethod()

It prints out No catch, while I expect it to print Catch! instead.


Solution

  • It's a bug in Groovy, there is an open issue in JIRA: Cannot override methods via metaclass that are part of an interface implementation, GROOVY-3493.