Last active
August 29, 2015 14:07
-
-
Save christoph-frick/448ae72f38e771fc67b5 to your computer and use it in GitHub Desktop.
@DeleGate and metaClass.invokeMethod as suggested in http://stackoverflow.com/questions/26407558/repetitive-try-catch-blocks-with-groovy-with-closure#26407700
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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