Groovy Goodness: Add Map Constructor With Annotation

Since the early days of Groovy we can create POGO (Plain Old Groovy Objects) classes that will have a constructor with a Map argument. Groovy adds the constructor automatically in the generated class. We can use named arguments to create an instance of a POGO, because of the Map argument constructor. This only works if we don’t add our own constructor and the properties are not final. Since Groovy 2.5.0 we can use the @MapConstrutor AST transformation annotation to add a constructor with a Map argument. Using the annotation we can have more options to customize the generated constructor. We can for example let Groovy generate the constructor with Map argument and add our own constructor. Also properties can be final and we can still use a constructor with Map argument.

First we look at the default behaviour in Groovy when we create a POGO:

Now let’s use the @MapConstructor annotation in our next example:

The AST transformation supports several attributes. We can use the attributes includes and excludes to include or exclude properties that will get a value in the Map argument constructor. In the following example we see how we can use the includes attribute:

We can add custom code that is executed before or after the generated code by the AST transformation using the attributes pre and post. We assign a Closure to these attributes with the code that needs to be executed.

In the next example we set the pre attribute with code that calculates the alias property value if it is not set via the constructor:

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 *