tags:

views:

47

answers:

2

Hi,

I'm trying to intercept all calls to properties on a Groovy class. Since this did not work as expected, I created the following example:

class TestClass {
    def getProperty(String key) {
        println "getting property: " + key
    }

    def invokeMethod(String method, args) {
        println "invoking method: " + method
    }

    def getFoo() {
        return 1
    }
}
tc.foo      // 1
tc.getFoo() // 2

1) does the right thing, that is getProperty is called. However, 2) works (i.e. 1 is returned) but neither getProperty nor invokeMethod is called.

Is there a way to intercept the getfoo() call as well?

Stefan

A: 

I wrote an article a couple of months ago. You can read it here.

Try this code :

TestClass.metaClass.invokeMethod = {
   def metaMethod = delegate.metaClass.getMetaMethod(method,args)
   println "executing $method with args $args on $delegate"
   return metaMethod.invoke(delegate,args)
}
Geo
A: 

I had to modify the code in a previous answer a bit to get what I think you want:

TestClass.metaClass.invokeMethod = {method, args ->
  def metaMethod = TestClass.metaClass.getMetaMethod(method,args)
  println "executing $method with args $args on $delegate"
  metaMethod.invoke(delegate,args) // could result in NPE
}

Then executing

tc.foo
tc.getFoo()

Results in:

getting property: foo                               // println output
null                                                // getProperty return is null
executing getFoo with args [] on TestClass@655538e5 // invokeMethod output
1                                                   // metaMethod invocation
MadJack