Groovy Goodness: Using Builder to Create Fluent API for Other Classes

In a previous post we learned about the new @Builder AST transformation introduced in Groovy 2.3. We applied to the annotation to our class files and we got a nice fluent API to set property values. But what if we cannot change the class itself, for example if we want to create a fluent API for classes in an external library. Then we can still use the @Builder AST transformation but we use a different strategy. We can define the builder strategy via a annotation parameter.

In the following sample we assume the Message class is from an external library and we cannot or do not want to change the class definition. We create a new Groovy class and set the @Builder annotation on this new class. We use the annotation parameters builderStrategy to indicate the generated code is not for the new class, but for the class set with the annotation parameter forClass.

We can also customize the prefix for the method names to set property values and we can change the name of the build method. And we can include or exclude properties with the includes and excludes properties:

Code written with Groovy 2.3.

Original article

This entry was posted in 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 *