【发布时间】:2012-03-20 11:43:45
【问题描述】:
我试图调试一些使用 mixins 的代码,并且我能够将我的问题简化为这个示例。我有一个通过 mixin 接收方法的父类和一个从父类继承的子类。如果我尝试替换子类实例上的方法,它会起作用除非,我要替换的方法在父类实例被替换之前被调用。如果它已被调用,那么我无法替换它
所以这段代码:
class M {
protected foo() { println 'foo' }
}
@Mixin(M) class A {
def bar() { foo() }
}
class B extends A {}
def b = new B()
def a = new A()
a.bar() //<-- comment out this line and see the difference
b.metaClass.foo = {println 'winning'}
b.bar()
将产生:
富
富
但是,如果您注释掉第 13 行(带有注释的那一行),您将得到:
获胜
为什么会这样?我希望这在 Groovy 的元类模型的上下文中是有意义的,但我不明白。
这是 Groovy 1.8.6
【问题讨论】:
-
我也可以在 Groovy 1.8.4 中重现这个。我闻起来像虫子;但我不太喜欢 Groovy 元编程,所以我不知道。
-
感谢您的说明,如果我最终提交错误,我一定会包括在内。
-
我会在 groovy 用户邮件列表上问这个问题,对我来说闻起来像一个错误......
-
这可能与任何方法处理程序缓存有关吗?
标签: inheritance groovy mixins metaclass