我在玩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!。
发布于 2012-09-05 21:35:52
这是Groovy中的一个bug,在JIRA中也有一个公开的问题:不能通过元类覆盖属于接口实现GROOVY-3493的方法。
发布于 2012-09-05 21:36:22
不要重写B.metaClass.myMethod,而是尝试执行以下操作:
B.metaClass.invokeMethod = {String methodName, args ->
println "Catch!"
}这个blog post很好地描述了这一点。
发布于 2015-07-01 03:49:19
有一个解决方法,但它只适用于所有类,而不适用于特定实例。
在构造之前修改元类:
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()https://stackoverflow.com/questions/12278477
复制相似问题