Java Magazine, Mar/Apr 2018
ORACLE COM JAVAMAGAZINE MARCH APRIL 2018 66 jvm languages Note the use of Groovys optional arguments as well another underrated feature Groovy also has closure currying closure composition using the shift operators and more Before going on to some of the other additions to Groovy I will show you what happens beneath the covers with AST transformations using macros as an example Macros First a note on terminology Groovy uses regular Java annotations to trigger code modifications done by the parser at compile time The compile time changes are called AST transformations and for each annotation such as @ ToString there is a corresponding AST transformation class org codehaus groovy transform ToStringASTTransformation The transformation class visits the various nodes of the syntax tree and modifies them as needed Writing a transformation class involves writing the node manipulation code creating nodes adding them to the tree and so on and thus requires deep knowledge of how the compiler generates the AST in the first place Although there are various utility and builder classes available to help writing an AST transformation is a tedious process What Groovy macros enable you to do is to write the transformation code as a regular Groovy method wrapped inside a macro block The compiler then converts the provided methods into the detailed node manipulation code for you Using an AST transformation is easy For example here the @ ToString annotation is added to a plain old Groovy object often referred to as a POGO import groovy transform @ ToString class Person String first String last The @ ToString annotation triggers an AST transformation via the ToStringASTTransformation class that generates a toString method during the compilation process and adds it to the com
You must have JavaScript enabled to view digital editions.