重写构造函数中调用的方法时,Groovy metaClass 失败? [英] Groovy metaClass fails when overriding method called in constructor?
问题描述
我只是尝试编写这个简单的代码来测试使用 metaClass 的覆盖方法.
I just tried to write this simple code to test overriding methods using metaClass.
代码在这里:
class Hello {
public Hello()
{
Foo()
}
public void Foo()
{
println "old"
}
}
它有一个 Foo() 方法,该方法简单地打印旧",并由构造函数调用.
It has a Foo() method which simply prints "old" and it was called by the constructor.
这是测试代码:
class HelloTest {
@Test
public void test() {
boolean methodFooWasCalled = false
Hello.metaClass.Foo = {-> println "new"
methodFooWasCalled = true
}
Hello hello = new Hello()
assertTrue methodFooWasCalled == true
}
}
我期待输出应该是新的",因为 Foo()
已被覆盖.但它仍然打印旧".有谁知道它为什么失败?谢谢
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
推荐答案
以下作品:
class Hello {
Hello() {
Foo()
}
}
Hello.metaClass.Foo = {->
println "new"
}
new Hello()
以下内容也是如此:
class Hello {
Hello() {
invokeMethod('Foo', [] as Object[])
}
void Foo() { println "old" }
}
Hello.metaClass.Foo = {->
println "new"
}
new Hello()
这个很有趣;在 Foo()
中的 bar()
调用有效,而在构造函数中的调用无效:
This one is interesting; the bar()
call inside Foo()
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()
Groovy 在构造函数上似乎不会首先检查元类的方法.我认为这是一个错误,我找不到与此相关的任何错误.填写 JIRA 怎么样?
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屋!