重写在构造函数中调用的方法时Groovy metaClass失败? [英] Groovy metaClass fails when overriding method called in constructor?
问题描述
我试图编写这个简单的代码来测试使用metaClass的重写方法。
代码在这里:
class Hello {
public Hello()
{
Foo()
}
public void Foo()
{
printlnold
}
}
它有一个Foo()方法,它简单地打印old,并且由构造函数调用。
测试代码:
class HelloTest {
已被覆盖。但它仍然印老。有谁知道它为什么会失败?谢谢
@Test
public void test() {
布尔methodFooWasCalled = false
Hello.metaClass.Foo = { - > printlnnew
methodFooWasCalled = true
}
Hello hello = new Hello()
assertTrue methodFooWasCalled == true
$ b我希望输出结果应该是新的, code> Foo()
解决方案以下工作:
class Hello {
Hello(){
Foo()
}
}
Hello.metaClass.Foo = { - >
printlnnew
}
new Hello()
$ p
$ bclass Hello {
Hello(){
invokeMethod ('Foo',[] as Object [])
}
void Foo(){printlnold}
}
您好。 metaClass.Foo = { - >
printlnnew
}
new Hello()
这一个很有趣;在
Foo()
中调用bar()
时会起作用,而构造函数中的那些不会:class Hello {
Hello(){
Foo()
bar()
}
void Foo(){printlnold foo; bar()}
void bar(){printlnold bar}
}
Hello.metaClass {
Foo = { - > printlnnew foo}
bar = {printlnnew bar}
}
new Hello()
看来Groovy在构造函数中没有检查元类的方法FIRST。我认为这是一个错误,我找不到与此相关的任何错误。填写 JIRA 怎么样?
I just tried to write this simple code to test overriding methods using metaClass.
The code is here:
class Hello { public Hello() { Foo() } public void Foo() { println "old" } }
It has a Foo() method which simply prints "old" and it was called by the constructor.
Here's the test code:
class HelloTest { @Test public void test() { boolean methodFooWasCalled = false Hello.metaClass.Foo = {-> println "new" methodFooWasCalled = true } Hello hello = new Hello() assertTrue methodFooWasCalled == true } }
I was expecting that the output should be "new" since
Foo()
has been overriden. But it still printed "old". Does anyone know why it fails? Thanks解决方案The following works:
class Hello { Hello() { Foo() } } Hello.metaClass.Foo = {-> println "new" } new Hello()
And so does the following:
class Hello { Hello() { invokeMethod('Foo', [] as Object[]) } void Foo() { println "old" } } Hello.metaClass.Foo = {-> println "new" } new Hello()
This one is interesting; the
bar()
call insideFoo()
works, whilst the ones inside the constructor doesn't:class Hello { Hello() { Foo() bar() } void Foo() { println "old foo"; bar() } void bar() { println "old bar" } } Hello.metaClass { Foo = {-> println "new foo" } bar = { println "new bar" } } new Hello()
It appears Groovy doesn't check metaclass' methods FIRST when on constructors. I think it is a bug, and i couldn't find any bug related to this. What about filling a JIRA?
这篇关于重写在构造函数中调用的方法时Groovy metaClass失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!