Is it possible to replace groovy method for existing object?

前端 未结 3 1768
终归单人心
终归单人心 2020-12-31 01:48

The following code tried to replace an existing method in a Groovy class:

class A {
  void abc()  {
     println \"original\"
  }
} 

x= new A()
x.abc()
A.me         


        
3条回答
  •  有刺的猬
    2020-12-31 02:08

    You can use the per-instance metaClass to change the value in the existing object like so:

    x= new A()
    x.abc()
    x.metaClass.abc={-> println "new" }
    x.abc()
    x.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"}
    

    But as you have seen, x will have two methods associated with it (well, in actual fact, a method and the closure you added

    If you change the definition of A so that the method becomes a closure definition like so:

    class A {
      def abc = { ->
         println "original"  
      }
    } 
    

    Then you will only get a single closure in the metaClass and no method after the alteration

提交回复
热议问题