views:

174

answers:

1

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.metaClass.abc={-> println "new" }
x.abc()
A.metaClass.methods.findAll{it.name=="abc"}.each { println "Method $it"}

new A().abc()

And it results in the following output:

original
original
Method org.codehaus.groovy.runtime.metaclass.ClosureMetaMethod@103074e[name: abc params: [] returns: class java.lang.Object owner: class A]
Method public void A.abc()
new

Does this mean that when modify the metaclass by setting it to closure, it doesn't really replace it but just adds another method it can call, thus resulting in metaclass having two methods? Is it possible to truly replace the method so the second line of output prints "new"?

When trying to figure it out, I found that DelegatingMetaClass might help - is that the most Groovy way to do this?

+2  A: 

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

tim_yates
Thanks - I am trying to use this to override a method in existing Groovy class, so I am trying to avoid modifying the original class.
Jean Barmash