I am trying to learn how to use (and extend) groovy, and I am following the example from this page . This basically shows how to define annotation for groovy code that allows you to connect to the compilation process. The example revolves around records and annotations that will cause lines to be printed before and after method calls.
My code is as follows; necessary import first:
package foo
import org.codehaus.groovy.transform.*
import java.lang.annotation.*
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.control.*
import org.codehaus.groovy.ast.stmt.*
import org.codehaus.groovy.ast.expr.*
Then we define the annotation to be used:
@Retention(RetentionPolicy.SOURCE)
@Target([ElementType.METHOD])
@GroovyASTTransformationClass(["foo.LoggingASTTransformation"])
public @interface WithLogging {
}
Then the conversion itself:
@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
public class LoggingASTTransformation implements ASTTransformation {
public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
println("visiting astnodes")
List methods = sourceUnit.getAST()?.getMethods()
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)
)
)
)
}
}
Finally, my code that should use this conversion:
public class Foo {
@WithLogging
def f() { println "hello from f" }
}
f = new Foo()
f.f()
Starting f\n hello from f\n Ending f, , , - f ( ). , , , - , , , ( ).
groovy -version Groovy Version: 1.6.0 JVM: 1.6.0_11
- , , , ?