Question

I got the same question as in In Groovy Is there a way to decorate every class to add tracing? but this answer is now several years old, so i wanted to know if there now is any better and more easy way to execute some code before, after or around the execution of methods. I would prefer something with annotations like

@TraceLog
class Foo {
   def bar() {
       println "in bar"
   }
}

or

class Foo { 
   @TraceLog
   def bar() {
       println "in bar"
   }
}

So that when i call bar(), some code (defined by TraceLog Aspect or similiar) is executed before "in bar" is printed. Is that possible with groovy yet?

Was it helpful?

Solution

You can do this via an AST transformation, as shown here

Care should be taken with that example however as the endMessage is just added as the last statement in the method. If the method has a return value, this is likely to be wrong...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top