【发布时间】:2012-03-02 06:46:49
【问题描述】:
当我将 invokeMethod 方法放到其中一个 mixin 类上时,我看到了一些我无法用 Groovy (1.8) mixins 解释的东西。
下面的测试证明了这种效果:
1: import java.net.Socket
2:
3: import org.junit.Test
4: import static org.junit.Assert.*
5:
6: class MixinPropertyTest {
7: static class Foo {
8: def message
9:
10: Object invokeMethod(String name, args) {
11: if (name != "println") {
12: println "invokeMethod sees ${message}"
13: println "invoking ${name}"
14: }
15: def metaMethod = metaClass.getMetaMethod(name, args)
16: metaMethod?.invoke(this, args)
17: }
18:
19: String message() {
20: message
21: }
22: }
23:
24: @Mixin(Foo)
25: static class Bar {
26: }
27:
28: @Test
29: void test() {
30: assertEquals 'hello', new Bar(message: 'hello').message()
31: }
32: }
此测试失败,输出如下:
invokeMethod sees hello
invoking message
但是,如果我剪掉 invokeMethod,它就会通过。 invokeMethod 在那里会导致它停止工作吗?
编辑:如果我在第 15 行和第 20 行设置断点,我将看到 this 分别为 MixinPropertyTest$Foo (id=43) 和 MixinPropertyTest$Foo (id=75)。在MetaMethod.invoke 调用过程中,我似乎正在与更改交互的Foo 实例。
【问题讨论】: