Skip to content

Instantly share code, notes, and snippets.

@dmahapatro
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmahapatro/385f2cd5138c31222859 to your computer and use it in GitHub Desktop.
Save dmahapatro/385f2cd5138c31222859 to your computer and use it in GitHub Desktop.
Debugging method calls using TracingInterceptor
/*
* Nice way to debug method calls by intercepting all method invocations
* on a GroovyObject using TracingInterceptor.
*/
class MyClass {
String name
def reverse() { name.reverse() }
def upperCase() { name.toUpperCase() }
def buggyMethod() { throw new Exception() }
}
def proxy = ProxyMetaClass.getInstance(MyClass.class)
proxy.interceptor = new TracingInterceptor()
println '** With constructor call interceptions ** '
// with constructor call interception
proxy.use {
def myObj = new MyClass( name: 'John Miller' )
assert myObj.reverse() == 'relliM nhoJ'
myObj.name = 'walter white'
assert myObj.upperCase() == 'WALTER WHITE'
}
println '\n** Avoid intercepting constructor calls ** '
// Avoid intercepting constructor calls
def myObj = new MyClass( name: 'John Miller' )
proxy.use( myObj ) {
assert myObj.reverse() == 'relliM nhoJ'
myObj.name = 'walter white'
assert myObj.upperCase() == 'WALTER WHITE'
// Only prints before interception
// After interceptor not reached
try { myObj.buggyMethod() } catch ( e ) { println 'Eating Exception' }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment