Groovy Goodness: Implement Interface And Abstract Methods Automatically

A lot of new AST transformation annotations are added in Groovy 2.5.0. One of them is the @AutoImplement annotation. If we apply this annotation to our class dummy implementations for abstract methods in superclasses or methods in implemented interfaces are created. This can be useful to have something in place and then gradually write real implementations for the abstract or interface methods. The transformation will not alter any method that is already implemented by custom code.

When we apply the @AutoImplement annotation the default implementation for an abstract method from a superclass or method from a interface is simple. If the method has a return type the default value of that return type is returned. For example false for a boolean and null for an object type. But the @AutoImplement annotation has some attributes we can use to change the default implementation. We can set the exception attribute and assign a exception type. The implementation of the methods is than to throw that exception when the method is invoked. With the optional message attribute we can set the exception message. Finally we can use the code attribute to define a Closure with statements that will be called as the implementation of abstract and interface methods.

In the following example we have an interface Creator and create several classes that implement this interface and apply the @AutoImplement annotation with different attribute values:

Written with Groovy 2.5.0.

Original post

This entry was posted in Coding, Groovy and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *