1

我在玩 Groovy,我想知道,为什么这段代码不起作用?

package test

interface A {
    void myMethod()
}

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

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

(new B()).myMethod()

它打印出来No catch,而我希望它打印出来Catch!

4

3 回答 3

9

这是 Groovy 中的一个错误,JIRA 中有一个未解决的问题:无法通过作为接口实现一部分的元类覆盖方法GROOVY-3493

于 2012-09-05T13:35:51.683 回答
1

而不是重写 B.metaClass.myMethod,请尝试以下操作:

 B.metaClass.invokeMethod = {String methodName, args ->
    println "Catch!"
 }

这篇博客文章很好地描述了它。

于 2012-09-05T13:36:21.620 回答
0

有一种解决方法,但它仅适用于所有类,而不适用于特定实例。

构建前的元类修改:

interface I {
    def doIt()
}

class T implements I {
    def doIt() { true }
}

I.metaClass.doIt = { -> false }
T t = new T()
assert !t.doIt()

构建后的元类修改:

interface I {
    def doIt()
}

class T implements I {
    def doIt() { true }
}

T t = new T()
// Removing either of the following two lines breaks this
I.metaClass.doIt = { -> false }
t.metaClass.doIt = { -> false }
assert !t.doIt()
于 2015-06-30T19:49:18.647 回答