重写构造函数中调用的方法时,Groovy 元类失败? [英] Groovy metaClass fails when overriding method called in constructor?

查看:24
本文介绍了重写构造函数中调用的方法时,Groovy 元类失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试编写这个简单的代码来测试使用元类的覆盖方法.

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() 方法,它简单地打印old"并被构造函数调用.

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()

这个很有趣;bar() 调用在 Foo() 中起作用,而构造函数中的调用不起作用:

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 元类失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆