Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
@WithLogging
def greet() {
     println "Hello World"
}

greet()

...

Code Block
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
public class LoggingASTTransformation implements ASTTransformation {

     public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
             List methods = sourceUnit.getAST()?.getMethods()
             // find all methods annotated with @WithLogging
             methods.findAll { MethodNode method ->
                      method.getAnnotations(new ClassNode(WithLogging))
             }.each { MethodNode method ->
                      Statement startMessage = createPrintlnAst("Starting $method.name")
                      Statement endMessage = createPrintlnAst("Ending $method.name")

                      List existingStatements = method.getCode().getStatements()
                      existingStatements.add(0, startMessage)
                      existingStatements.add(endMessage)
             }
     }

     private Statement createPrintlnAst(String message) {
             return new ExpressionStatement(
                      new MethodCallExpression(
                              new VariableExpression("this"),
                              new ConstantExpression("println"),
                              new ArgumentListExpression(
                                      new ConstantExpression(message)
                              )
                      )
             )
     }
}

Starting at the top...

...

Code Block
@WithLogging
def greet() {
     println "Hello World"
}

greet()

...