Compile Time Meta Programming in Groovy
Today at gr8conf–which by the way is a grait conference–I heard Guillaume LaForge, talk about the new stuff in groovy 1.6. One of those being AST transformations or what they call compile time meta programming.
Through annotations, one is able to tell the compiler to change the code, before it is producing actual byte-code output from the AST. One example is the ever present Singleton “pattern”, which is implemented as an annotation, like this:
@Singleton
public class SingletonTest {
}
new SingletonTest()
When run, this code will produce an exception at runtime, like this:
Caught: java.lang.RuntimeException: Can't instantiate singleton SingletonTest. Use SingletonTest.instance
at SingletonTest.<init>(SingletonMain.groovy)
at SingletonMain.run(SingletonMain.groovy:4)
What happens here is, that the compiler is producing a singleton from SingletonTest, putting a property “instance” on the class, at compile-time.
I guess stuff like this are making the job even harder for IDE developers. Not only do they not get as much type information to work with as with statically typed languages, but also shall they know about meta-programming like this, that changes the code when compiled. The code above does not color red in IDEA (yet).
May 18, 2009
Tags: groovy Posted in: Programming

Leave a Reply