I have a lot of boilerplate code that basically follows this pattern:
function doSomething() {
try {
[implementation]
[implementation]
[implementation]
[implementation]
} catch (Exception e) {
MyEnv.getLogger().log(e);
} finally {
genericCleanUpMethod();
}
}
I’d love to create my own annotation to clean my code up a bit:
@TryCatchWithLoggingAndCleanUp
function doSomething() {
[implementation]
[implementation]
[implementation]
[implementation]
}
The method signatures vary wildly (depending on the actual implementation of the method), but the boilerplate try/catch/finally part is always the same.
The annotation I have in mind would automatically wrap the contents of the annotated method with the whole try...catch...finally hoopla.
I’ve searched high and low for a straightforward way to do this, but have found nothing. I don’t know, maybe I just can’t see the woods for all the annotated trees.
Any pointers on how I might implement such an annotation would be greatly appreciated.
To do this, you would need some AOP framework that would use a proxy around your method. This proxy would catch the exception and execute the finally block. Quite frankly, if you don’t use a framework supporting AOP already, I’m not sure I would use one just to save these few lines od code.
You could use the following pattern to do this in a more elegant way, though:
I just used
Callable<Void>as an interface, but you could define your ownCommandinterface:and thus avoid the need to use a generic
Callable<Void>and return null from the Callable.EDIT: in case you want to return something from your methods, then make the
logAndCleanup()method generic. Here’s a complete example:EDIT : And with Java 8, the wrapped code can be a bit prettier :