Intercepting Method Call in Groovy and Invoking the Original Method

Groovy metaClass allows you to dynamically add or replace method of any Java or Groovy class during runtime:

1
2
3
4
        FooClass.metaClass.someMethod = { args ->
            // your method implementation
            // you can call delegate.someOtherMethod
        }

Using delegate you can invoke any other method of the instance. Now, what if FooClass.someMethod already exists and you just want to intercept the call and invoke the original implementation? If you try to call delegate.someMethod you’ll end up with the StackOverflowException because call is “routed” to your implementation of the method, not to the original.This can be solved simply saving a reference to the original method before replacing it:

1
2
3
4
5
6
7
        def originalMethod = FooClass.metaClass.getMetaMethod("someMethod", method_arguments)
        FooClass.metaClass.someMethod = { args ->
            // do whatever you do before...
            def result = originalMethod.invoke(delegate,args)
            // ... or after you invoke the original
            result
        }

Comments