Groovy metaClass fails when overriding method called in constructor?

前端 未结 1 1886
悲&欢浪女
悲&欢浪女 2020-12-20 15:03

I just tried to write this simple code to test overriding methods using metaClass.

The code is here:

class Hello {

    public Hello()  
    {
              


        
相关标签:
1条回答
  • 2020-12-20 15:08

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

    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?

    0 讨论(0)
提交回复
热议问题