Skip to content

Instantly share code, notes, and snippets.

@melix
Created December 12, 2013 14:11
Show Gist options
  • Save melix/7928511 to your computer and use it in GitHub Desktop.
Save melix/7928511 to your computer and use it in GitHub Desktop.
Using an existing annotation as to trigger AST transformations. This sample compiles a class which is annotated with @entity, and we want to transparently apply @tostring(includeNames=true) to it.
import org.codehaus.groovy.control.CompilerConfiguration
import groovy.transform.ToString
import static org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder.*
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
def cc = new CompilerConfiguration()
withConfig(cc) {
inline(phase: 'CONVERSION') { source, context, classNode ->
if (classNode.annotations.any { it.classNode.name == 'Entity' }) {
new ASTTransformationCustomizer(ToString, includeNames:true).call(source, context, classNode)
}
}
}
def shell = new GroovyShell(cc)
shell.evaluate '''@interface Entity {}
@Entity
class Person {
String name
int age
}
new Person(name:'Bob', age: 40)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment