Skip to content

Instantly share code, notes, and snippets.

@christoph-frick
Last active August 29, 2015 14:07
Show Gist options
  • Save christoph-frick/448ae72f38e771fc67b5 to your computer and use it in GitHub Desktop.
Save christoph-frick/448ae72f38e771fc67b5 to your computer and use it in GitHub Desktop.
class Widget {
void doStuff() { println 'doing stuff' }
String sayStuff(String name) { return "Hello $name" }
void fail() { throw new RuntimeException("Boom") }
}
class WidgetService {
// our service now has all the methods, Widget has
@Delegate Widget widget = new Widget()
// adding other stuff is fine too
String somethingDifferent() { println "Works also" }
}
// wrap all method invocations on WidgetService
WidgetService.metaClass.invokeMethod = { String name, args ->
println "Running $name with $args"
try {
// call the original method from WidgetService, which itself might be delegated to Widget
result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
}
catch (Exception e) {
println "Failed with: $e.message"
}
println "Result: $result"
result
}
// WidgetService now behaves like a Widget + has it's own functionality
// and all s wrapped in one central helper
def ws = new WidgetService()
ws.doStuff()
ws.fail()
ws.sayStuff("World")
ws.somethingDifferent()
// output:
// Running doStuff with []
// doing stuff
// Result: null
// Running fail with []
// Failed with: Boom
// Result: null
// Running sayStuff with [World]
// Result: Hello World
// Running somethingDifferent with []
// Works also
// Result: null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment