Search

Dark theme | Light theme
Showing posts with label GroovyGoodness:AST. Show all posts
Showing posts with label GroovyGoodness:AST. Show all posts

September 5, 2025

Groovy Goodness: Map Methods To Operators

Groovy supports operator overloading since the start. Operator overloading is implemented by an actual method signature that maps to an operator. For example an object with a plus method can be used with the + operator. There is a list of methods and operators available on the Groovy website.
As long as an object has a method with a name that Groovy understands the corresponding operator can be used in Groovy code. This is even true for Java objects. Since Groovy 5 you can use the groovy.transform.OperatorRename annotation on classes, methods or constructors to map other method names to the Groovy operator overloading method names. This is very useful for third-party classes that you cannot change, but still want to use simple operators in Groovy code. You can reassign a method name to the following methods so an operator can be used: plus, minus, multiply, div, remainder, power, leftShift, rightShift, rightShiftUnassigned, and, or, xor, compareTo. Suppose you use a class with an add method and want to use the + operator for this method. The following annotation can be used @OperatorRename(plus = 'add') for a method and inside the method you can use the + operator instead of the add method of the class.

October 9, 2023

Groovy Goodness: Using NullCheck Annotation To Prevent NullPointerException

In Groovy we can apply the @NullCheck annotation to a class, constructor or method. The annotation is an AST (Abstract Syntax Tree) transformation and will insert code that checks for null values in methods or constructors. If a null value is passed to an annotated method or constructor, it will throw an IllegalArgumentException. Without the annotation we could have a NullPointerException if we try to invoke a method on the value we pass as argument. The annotation has an optional property includeGenerated which by default is false. If we set it to true then the null checks are also applied to generated methods and constructors. This is very useful if we apply other AST transformations to our class that generates additional code.

In the following example we use the @NullCheck annotation for a method and at class level:

import groovy.transform.NullCheck

@NullCheck
String upper(String value) {
    "Upper:" + value.toUpperCase()
}

assert upper("groovy") == "Upper:GROOVY"

try {
    upper(null)
} catch (IllegalArgumentException e) {
    assert e.message == "value cannot be null"
}
import groovy.transform.NullCheck

// Apply null check for all constructors and methods.
@NullCheck
class Language {
    private String name

    Language(String name) {
       this.name = name;
    }

    String upper(String prefix) {
        return prefix + name.toUpperCase();
    }
}


def groovy = new Language("groovy")

assert groovy.upper("Upper:") == "Upper:GROOVY"

// Method arguments are checked.
try {
    groovy.upper(null)
} catch (IllegalArgumentException e) {
    assert e.message == "prefix cannot be null"
}

// Constructor argument is also checked.
try {
    def lang = new Language(null)
} catch (IllegalArgumentException e) {
    assert e.message == "name cannot be null"
}

In the following example we set the includeGenerated property to true to also generate null checks for generated code like the constructor generated by @TupleConstructor:

import groovy.transform.NullCheck
import groovy.transform.TupleConstructor

@NullCheck(includeGenerated = true)
@TupleConstructor
class Language {
    final String name

    String upper(String prefix) {
        return prefix + name.toUpperCase();
    }
}

// Constructor is generated by @TupleConstructor and
// @NullCheck is applied to the generated constructor.
try {
    def lang = new Language(null)
} catch (IllegalArgumentException e) {
    assert e.message == "name cannot be null"
}

Written with Groovy 4.0.13

June 22, 2018

Groovy Goodness: Creating Extra Method Supporting Named Arguments Using @NamedVariant Annotation

Groovy supports named arguments for methods. Actually Groovy collects all named arguments (defined using the name followed by a : and the value) into a Map. The Map must be the first parameter of the method to make it all work. Since Groovy 2.5.0 we can use the @NamedVariant AST transformation annotation to let Groovy create a method where the first parameter is a Map to support named arguments for an existing method. The existing method is still available, but Groovy adds an extra method to our generated class.

By default Groovy will make the first parameters of the original method part of the new method supporting named arguments. If the first parameters is a class type, then the properties of the class can be used as named arguments. We can also explicitly define which parameters of our original method should be named arguments using the annotations @NamedParam and @NamedDelegate. These annotations need to defined for each parameter. The newly created method by the AST transformation invokes the original method.

In the following example we use @NamedVariant for the ConferenceMaker.copy method:

import groovy.transform.NamedVariant
import groovy.transform.NamedDelegate

class Conference {
    String name, location
}

class ConferenceMaker {
    // First parameter's properties will be the 
    // named arguments we can use. Optionally
    // we could add @NamedDelegate before the
    // parameter definition.
    @NamedVariant
    static Conference copy(Conference conf) {
        new Conference(name: conf.name, location: conf.location)
    }

    // We use @NamedDelegate to let the properties of the
    // second parameter be named arguments for the newly
    // created method.
    @NamedVariant
    static Conference copy(boolean upper, @NamedDelegate Conference conf) {
        upper ? new Conference(name: conf.name.toUpperCase(), location: conf.location.toUpperCase())
              : new Conference(name: conf.name, location: conf.location)
    }
}


// All properties of the type of the argument (Conference)
// can be used as named arguments.
def greach = ConferenceMaker.copy(name: 'Greach', location: 'Madrid')

assert greach.name == 'Greach'
assert greach.location == 'Madrid'

// Parameter upper in original method definition is not
// part of the named arguments.
def gr8conf = ConferenceMaker.copy(name: 'Gr8Conf', true, location: 'Copenhagen')

assert gr8conf.name == 'GR8CONF'
assert gr8conf.location == 'COPENHAGEN'

In the next example we use @NamedParam to define the parameters that need to be used as named arguments. We can use the attribute required to indicate the named argument must be provided otherwise an error is thrown:

import static groovy.test.GroovyAssert.shouldFail

import groovy.transform.NamedVariant
import groovy.transform.NamedParam

class Conference {
    String name, location
}

class ConferenceMaker {
    // Using @NamedVariant to create
    // also an implementation of the make 
    // method with a Map argument to 
    // support named arguments.
    @NamedVariant
    static Conference make(
        @NamedParam(required = true) String name, 
        @NamedParam String location) {
        
        new Conference(name: name, location: location)
    }
}

// The named argument 'name' is required,
// 'location' is optional.
def gr8Conf = ConferenceMaker.make(name: 'Gr8Conf')

assert gr8Conf.name == 'Gr8Conf'

def required = shouldFail(AssertionError) {
    // If we don't specify the required named
    // argument an exception is thrown.
    ConferenceMaker.make(location: 'Copenhagen')
}
assert required.message.contains("Missing required named argument 'name'.")


// With named arguments the order of the arguments
// is not important.
def gr8ConfEU = ConferenceMaker.make(location: 'Copenhagen', name: 'Gr8Conf')

assert gr8ConfEU.name == 'Gr8Conf'
assert gr8ConfEU.location == 'Copenhagen'


shouldFail(MissingMethodException) {
    // Because the original make method is
    // invoked by the generated named arguments make 
    // method, so we get an exception when
    // the type of the named argument is incorrect.
    ConferenceMaker.make(name: 'G' as char)
}

Written with Groovy 2.5.0.

June 19, 2018

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:

// Simple POGO.
// Groovy adds Map argument
// constructor to the class.
class Person {
    String name
    String alias
    List<String> likes
}

// Create Person object using
// the Map argument constructor.
// We can use named arguments, 
// with the name of key being
// the property name. Groovy
// converts this to Map.
def mrhaki = 
    new Person(
        alias: 'mrhaki',
        name: 'Hubert Klein Ikkink',
        likes: ['Groovy', 'Gradle'])
        
assert mrhaki.alias == 'mrhaki'
assert mrhaki.name == 'Hubert Klein Ikkink'
assert mrhaki.likes == ['Groovy', 'Gradle']


// Sample class with already
// a constructor. Groovy cannot
// create a Map argument constructor now.
class Student {
    String name
    String alias
    
    Student(String name) {
        this.name = name
    }
}


import static groovy.test.GroovyAssert.shouldFail

// When we try to use named arguments (turns into a Map)
// in the constructor we get an exception.
def exception = shouldFail(GroovyRuntimeException) {
    def student = 
        new Student(
            name: 'Hubert Klein Ikkink', 
            alias: 'mrhaki')
}

assert exception.message.startsWith('failed to invoke constructor: public Student(java.lang.String) with arguments: []')
assert exception.message.endsWith('reason: java.lang.IllegalArgumentException: wrong number of arguments')

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

import groovy.transform.MapConstructor

@MapConstructor
class Person {
    final String name // AST transformation supports read-only properties.
    final String alias
    List<String> likes
}

// Create object using the Map argument constructor.
def mrhaki = 
    new Person(
        name: 'Hubert Klein Ikkink', 
        alias: 'mrhaki', 
        likes: ['Groovy', 'Gradle'])
        
assert mrhaki.name == 'Hubert Klein Ikkink'
assert mrhaki.alias == 'mrhaki'
assert mrhaki.likes == ['Groovy', 'Gradle']

// Using the annotation the Map argument
// constructor is added, even though we
// have our own constructor as well.
@MapConstructor
class Student {
    String name
    String alias
    
    Student(String name) {
        this.name = name
    }
}

def student = 
    new Student(
        name: 'Hubert Klein Ikkink', 
        alias: 'mrhaki')
        
assert student.name == 'Hubert Klein Ikkink'
assert student.alias == 'mrhaki'

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:

import groovy.transform.MapConstructor

@MapConstructor(includes = 'name')
class Person {
    final String name 
    final String alias
    List<String> likes
}

// Create object using the Map argument constructor.
def mrhaki = 
    new Person(
        name: 'Hubert Klein Ikkink', 
        alias: 'mrhaki', 
        likes: ['Groovy', 'Gradle'])
        
assert mrhaki.name == 'Hubert Klein Ikkink'
assert !mrhaki.alias 
assert !mrhaki.likes 

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:

// If alias is set in constructor use it, otherwise
// calculate alias value based on name value.
@MapConstructor(post = { alias = alias ?: name.split().collect { it[0] }.join() })
class Person {
    final String name // AST transformation supports read-only properties.
    final String alias
    List<String> likes
}

// Set alias in constructor.
def mrhaki = 
    new Person(
        name: 'Hubert Klein Ikkink', 
        alias: 'mrhaki', 
        likes: ['Groovy', 'Gradle'])
        
assert mrhaki.name == 'Hubert Klein Ikkink'
assert mrhaki.alias == 'mrhaki'
assert mrhaki.likes == ['Groovy', 'Gradle']

// Don't set alias via constructor.
def hubert = 
    new Person(
        name: 'Hubert A. Klein Ikkink')
        
assert hubert.name == 'Hubert A. Klein Ikkink'
assert hubert.alias == 'HAKI'
assert !hubert.likes

Written with Groovy 2.5.0.

June 15, 2018

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:

import groovy.transform.AutoImplement
import static groovy.test.GroovyAssert.shouldFail

// Sample class with two simple properties.
@groovy.transform.Canonical
class Course {
    String name, location
}

// Interface with a single method to 
// create an object based on Map argument.
interface Creator<R> {
    R create(Map args)
}


// Use AutoImplement annotation to create object
// implementing the Creator interface. The compiled
// class will have an implementation for the create
// method. The return value is the default of the
// return type, in our case null.
@AutoImplement
class DefaultCourseCreator implements Creator<Course> { }

def defaultCreator = new DefaultCourseCreator()
assert defaultCreator.create(name: 'Groovy', location: 'Tilburg') == null


// When we use the AutoImplement annotation, only
// methods that are not implemented by ourselves
// will have an auto implementation.
@AutoImplement
class ImplCourseCreator implements Creator<Course> { 
    Course create(Map args) {
        new Course(args)
    }
}

def creator = new ImplCourseCreator()
assert creator.create(name: 'Groovy', location: 'Tilburg') == new Course(name: 'Groovy', location: 'Tilburg')


// Instead of returning the default value for the return type,
// we can throw an exception as default implementation.
// We can specify the type of exception and optionally the
// exception message.
@AutoImplement(exception = UnsupportedOperationException, 
               message = 'Not supported by NotSupportedCourseCreator')
class NotSupportedCourseCreator implements Creator<Course> { }

def creatorUnsupported = new NotSupportedCourseCreator()

def exception = shouldFail(UnsupportedOperationException) {
    creatorUnsupported.create(name: 'Groovy 101')
}
assert exception.message == 'Not supported by NotSupportedCourseCreator'


// We can use the code attribute of the AutoImplement annotation to
// specify a Closure. The Closure is used as implementation for the
// method from the interface.
// In this case we log a warning and return null as value. Notice
// we can access the log variable added by the Log annotation in 
// the Closure of the code attribute.
@groovy.util.logging.Log
@AutoImplement(code = { log.warning('Method needs implementation'); return null })
class ImplementCodeCourseCreator implements Creator<Course> { }

def creatorWarning = new ImplementCodeCourseCreator()
assert !creatorWarning.create(name: 'Groovy') // Prints log message "WARNING: Method needs implementation"

Written with Groovy 2.5.0.

June 23, 2016

Groovy Goodness: Customise Log AST Annotations

Adding logging support to a class in Groovy is easy. We can choose to add SLF4J, Log4j, Log4j2, Apache Commons or Java Util Logging to our class. The default implementation of the Abstract Syntax Tree (AST) transformation is to add a log field of the correct type. As category name the complete class name (including the package) is used. We can change the name of the field with the value attribute. To alter the category name we use the attribute category.

In the following example snippet we change the log field name to LOGGER and set a custom category name:

@Grapes(
    @Grab(group='ch.qos.logback', module='logback-classic', version='1.1.7')
)
import groovy.util.logging.Slf4j

// Change name of the field to LOGGER and
// the category to 'mrhaki.blog.samples'.
@Slf4j(value = 'LOGGER', category = 'mrhaki.blog.samples')
class SampleLogging {

    String sample(final String message) {
        LOGGER.info 'Running sample({}) method', message
        
        "Groovy is $message!"
    }
    
}

def s = new SampleLogging()
println "System.out says: ${s.sample('gr8')}"

When we execute the script we get the following output:

16:33:56.972 [Thread-7] INFO mrhaki.blog.samples - Running sample(gr8) method
System.out says: Groovy is gr8!

Notice the category is mrhaki.blog.samples and we use the field LOGGER in our code.

Written with Groovy 2.4.7.

May 26, 2016

Groovy Goodness: Make Class Cloneable With @AutoClone

Groovy has many AST annotations that add code to our class (the Abstract Syntax Tree - AST) before it is compiled. So the compiled class file contains the code added by the AST annotation. With the @AutoClone annotation a clone method is added and the class implements the Cloneable interface. We have different strategies to choose from to support cloning for our class.

The default strategy is to invoke super.clone() in the generated clone method. The next statements will deep copy the properties (and optional fields) from our class. If one of the properties cannot be cloned an exception is thrown. In the following example code snippet we apply the @AutoClone annotation to the classes Course and Teacher:

import groovy.transform.AutoClone

@AutoClone
class Course {
    String name
    Date date
    Teacher teacher
}

@AutoClone
class Teacher {
    String name
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)

// We make a deep copy.
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
assert secondCourse.teacher != course.teacher

// Change property on cloned instance.
secondCourse.name = 'Groovy 101 2nd edition'

assert secondCourse.name == 'Groovy 101 2nd edition'
assert course.name == 'Groovy 101'

We can use the excludes annotation attribute to give a list of properties that must not be cloned:

import groovy.transform.AutoClone

// Do not clone the teacher property.
@AutoClone(excludes = ['teacher'])
class Course {
    String name
    Date date
    Teacher teacher
}

@AutoClone()
class Teacher {
    String name
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)

// We make a deep copy.
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
// Only the teacher property is
// a shallow copy.
assert secondCourse.teacher == mrhaki
assert secondCourse.teacher.is(mrhaki)

// Change property on teacher property on cloned instance.
secondCourse.teacher.name = 'hubert'

assert secondCourse.teacher.name == 'hubert'
assert course.teacher.name == 'hubert'

To include fields as well as properties we must set the annotation attribute includeFields to true.

If we want to invoke the default constructor of our class in the clone method we must use the clone style AutoCloneStyle.SIMPLE. In the generated clone method the constructor is invoked followed by copying the properties:

import groovy.transform.AutoClone
import static groovy.transform.AutoCloneStyle.SIMPLE

@AutoClone(style = SIMPLE)
class Course {
    String name
    Date date
    Teacher teacher
    
    static int counter
    
    Course() {
        counter++
    }
}

@AutoClone(style = SIMPLE)
class Teacher {
    String name
    
    static int counter
    
    Teacher() {
        counter++
    }
}

def mrhaki =
    new Teacher(name: 'mrhaki')
    
def course = 
    new Course(
        name: 'Groovy 101',
        date: new Date() + 10,
        teacher: mrhaki)
        
def otherCourse = course.clone()

// Constructor is invoked twice:
// once by ourselves to create a 
// course, the other by the clone()
// method added by @AutoClone.
assert course.counter == 2
assert course.teacher.counter == 2

The last clone style we can choose is AutoCloneStyle.COPY_CONSTRUCTOR. This time the annotation will add a protected constructor that takes another object of the same type as argument. This new constructor is used in the generated clone method. This style is useful if we have final read-only properties that can only be set via the constructor:

import groovy.transform.AutoClone
import static groovy.transform.AutoCloneStyle.COPY_CONSTRUCTOR

@AutoClone(style = COPY_CONSTRUCTOR)
class Course {
    final String name
    final Date date
    final Teacher teacher
    
    Course(
        final String name,
        final Date date,
        final Teacher teacher) {
        
        this.name = name
        this.date = date
        this.teacher = teacher
    }
}

@AutoClone(style = COPY_CONSTRUCTOR)
class Teacher {
    final String name
    
    Teacher(final String name) {
        this.name = name
    }
}

def mrhaki =
    new Teacher('mrhaki')
    
def course = 
    new Course(
        'Groovy 101',
        new Date() + 10,
        mrhaki)
        
def secondCourse = course.clone()
assert secondCourse != course
assert !secondCourse.is(course)
assert secondCourse.teacher != mrhaki
assert !secondCourse.teacher.is(mrhaki)

This annotation was already available since Groovy 1.8.

Written with Groovy 2.4.6.

May 5, 2014

Groovy Goodness: Use Sortable Annotation to Make Classes Comparable

Since Groovy 2.3 we can use the @Sortable annotation to make a class implement the Comparable interface. Also new comparator methods are added. All properties of a class are used to implement the compareTo method. The order of the properties determines the priority used when sorting. With the annotation parameters includes and excludes we can define which properties of the class need to be used to implement the compareTo method.

In the following class with the name Course we define three properties title, beginDate and maxAttendees. We also apply the @Sortable annotation. Notice we cannot use int as a type, because it doesn't implement the Comparable interface. The class Integer does.

import groovy.transform.Sortable
import groovy.transform.ToString

@Sortable
@ToString
class Course {
    // Order of properties determines priority when sorting
    String title
    Date beginDate
    Integer maxAttendees  // int doesn't implement Comparable, so use Integer
}


final Course groovy = new Course(
        title: 'Groovy', beginDate: new Date() + 7, maxAttendees: 40)
final Course groovy2 = new Course(
        title: 'Groovy', beginDate: new Date() + 2, maxAttendees: 50)
final Course grails = new Course(
        title: 'Grails', beginDate: new Date() + 1, maxAttendees: 20)


final List<Course> courses = [groovy, groovy2, grails]
assert courses.last().title == 'Grails'

// Use sort() method to sort
final List<Course> sorted = courses.sort(false /* do not mutate original collection */)

assert sorted.first().title == 'Grails'
assert sorted.last().title == 'Groovy'
assert sorted.maxAttendees == [20, 50, 40]

If we only want the properties title and maxAttendees to be used in the compareTo method we define those properties with the includes parameter:

// Order of fields for includes determines priority when sorting
@Sortable(includes = ['title', 'maxAttendees'])
// Or @Sortable(excludes = ['beginDate'])
@ToString
class CourseSort {
    String title
    Date beginDate
    Integer maxAttendees
}

final Course groovy = new Course(
        title: 'Groovy', beginDate: new Date() + 7, maxAttendees: 40)
final Course groovy2 = new Course(
        title: 'Groovy', beginDate: new Date() + 2, maxAttendees: 50)
final Course grails = new Course(
        title: 'Grails', beginDate: new Date() + 1, maxAttendees: 20)


final List<Course> courses = [groovy, groovy2, grails]

// Use sort() method to sort
final List<Course> sorted = courses.sort(false)

assert sorted.first().title == 'Grails'
assert sorted.last().title == 'Groovy'
assert sorted.maxAttendees == [20, 40, 50]

Besides implementing the Comparable interface with a compareTo method, the AST transformation also adds public static methods with the pattern comparatorByProperty. These methods return a Comparator object for the given property.

final Comparator byMaxAttendees = Course.comparatorByMaxAttendees()
final List<Course> sortedByMaxAttendees = courses.sort(false, byMaxAttendees)

assert sortedByMaxAttendees.maxAttendees == [20, 40, 50]
// beginDate is not used for sorting
assert sortedByMaxAttendees[2].beginDate < sortedByMaxAttendees[1].beginDate

assert Course.declaredMethods.name.findAll { it.startsWith('comparatorBy') } == ['comparatorByTitle', 'comparatorByMaxAttendees']

Code written with Groovy 2.3.

Groovy Goodness: @Builder Definition with Extra Type Checks

We have seen some features of the @Builder AST transformation in previous and other blog post. We can use another strategy to let the AST transformation generate a class where the class only has a constructor that accepts a builder class. And with @CompileStatic we can even make sure that all required properties must have a value set by the builder before the constructor accepts the argument. We use the builderStrategy annotation parameter and set it to InitializerStrategy:

import groovy.transform.builder.Builder
import groovy.transform.builder.InitializerStrategy

@Builder(builderStrategy = InitializerStrategy)
class Message {
    String from, to, subject, body
}

def message = Message.createInitializer()
        .from('mrhaki@mrhaki.com')
        .subject('Groovy 2.3 is released')

// Returned object is not Message, but
// internal class Message$MessageInitializer
assert !(message instanceof Message)

// Now we can use the initializer in the
// only constructor of Message.
def messageInstance = new Message(message)

assert messageInstance instanceof Message
assert messageInstance.from == 'mrhaki@mrhaki.com'
assert messageInstance.subject == 'Groovy 2.3 is released'

We can customize which properties need to be set with the includes and/or excludes annotation parameter. We can also customize the name of the method that create the builder instance with the parameter builderMethodName:

package com.mrhaki.blog.groovy

import groovy.transform.CompileStatic
import groovy.transform.builder.Builder
import groovy.transform.builder.InitializerStrategy

@Builder(builderStrategy = InitializerStrategy,
        excludes = 'body',
        builderMethodName = 'creator')
class Message {
    String from, to, subject, body
}

// With @CompileStatic the compiler will check
// that all properties defined in the @Builder
// configuration are set. This way we can
// implement required properties for a class
// that need to be set before the object can
// be created.
@CompileStatic
def createMessage() {
    def messageInit = Message.creator()
            .from('mrhaki@mrhaki.com')
            .to('mail@host.nl')
            .subject('Groovy 2.3 is released')

    def message = new Message(messageInit)
    message
}

final Message message = createMessage()

assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Groovy 2.3 is released'

Code written with Groovy 2.3.

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.

import groovy.transform.builder.Builder
import groovy.transform.builder.ExternalStrategy

// We don't want to change the definition
// of this class to get a fluent API.
class Message {
    String from, to, subject, body
}

// New builder class for the Message class.
@Builder(builderStrategy = ExternalStrategy, forClass = Message)
class MessageBuilder {}

def message = new MessageBuilder()  // Create new instance.
        .from('mrhaki@mrhaki.com')
        .to('mail@host.nl')
        .subject('Groovy 2.3 is released')
        .body('Groovy rocks!')
        .build()  // Return filled Message instance.

assert message.body == 'Groovy rocks!'
assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Groovy 2.3 is released'

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:

import groovy.transform.builder.Builder
import groovy.transform.builder.ExternalStrategy

class Message {
    String from, to, subject, body
}

@Builder(builderStrategy = ExternalStrategy, forClass = Message,
        prefix = 'assign', buildMethodName = 'create',
        includes = 'from,subject')
class MessageBuilder {}

def message = new MessageBuilder()
        .assignFrom('mrhaki@mrhaki.com')
        .assignSubject('Groovy 2.3 is released')
        .create()

assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Groovy 2.3 is released'

Code written with Groovy 2.3.

Groovy Goodness: Use Builder AST Transformation for Fluent API

Since Groovy 2.3 we can easily create a fluent API for our classes with the @Builder AST transformation. We can apply the annotation to our classes and the resulting class file will have all the necessary methods to support a fluent API. We can customize how the fluent API is generated with different annotation parameters. In Groovy code we already can use the with method to have a clean way to set property values or use the named constructor arguments. But if our classes need to be used from Java it is nice to give the Java developers a fluent API for our Groovy classes.

In the following sample we apply the @Builder annotation to a simple class Message with some properties. We leave everything to the default settings and then the resulting Message class file will have a new builder method that return an internal helper class we can use to set our properties. For each property their is a new method with the name of the property so we can set a value. And finally our class contains a build that will return a new instance of the Message class with the correct values for the properties.

import groovy.transform.builder.Builder

@Builder
class Message {
    String from, to, subject, body
}

def message = Message
        .builder()  // New internal helper class.
        .from('mrhaki@mrhaki.com')  // Method per property.
        .to('mail@host.nl')
        .subject('Sample mail')
        .body('Groovy rocks!')
        .build()  // Create instance of Message

assert message.body == 'Groovy rocks!'
assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Sample mail'
assert message.to == 'mail@host.nl'

If we want to change the names of the builder and build methods we can use the annotation parameters builderMethodName and buildMethodName:

import groovy.transform.builder.Builder

@Builder(builderMethodName = 'initiator', buildMethodName = 'create')
class Message {
    String from, to, subject, body
}

def message = Message.initiator()
        .from('mrhaki@mrhaki.com')
        .body('Groovy rocks!')
        .create()

assert message.body == 'Groovy rocks!'
assert message.from == 'mrhaki@mrhaki.com'

We see that for each property a corresponding method is generated. We can also customize the prefix for the generated method name with the annotation parameter prefix. In the following sample we define the prefix assign for the method names:

import groovy.transform.builder.Builder

@Builder(prefix = 'assign')
class Message {
    String from, to, subject, body
}

def message = Message.builder()
        .assignFrom('mrhaki@mrhaki.com')
        .assignBody('Groovy rocks!')
        .build()

assert message.body == 'Groovy rocks!'
assert message.from == 'mrhaki@mrhaki.com'

Finally we can also include and exclude properties to need to be included or excluded from our fluent API. We use the annotation parameters includes and excludes to define the names of the properties. This can be a list or a comma separated list of names.

import groovy.transform.builder.Builder

@Builder(excludes = 'body' /* or includes = 'from,to,subject' */)
class Message {
    String from, to, subject, body
}

def message = Message.builder()
        .from('mrhaki@mrhaki.com')
        .to('mail@host.nl')
        .subject('Groovy 2.3 is released')
        .build()

assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Groovy 2.3 is released'

try {
    message = Message.builder().body('Groovy rocks!').build()
} catch (MissingMethodException e) {
    assert e.message.readLines().first() ==
            'No signature of method: static Message.body() is applicable for argument types: (java.lang.String) values: [Groovy rocks!]'
}

The @Builder AST transformation also checks if the @Canonical AST transformation is applied to a class. Any included or excluded properties defined in the @Canonical transformation are also included or excluded for the generated builder code.

We can define the SimpleStrategy strategy with the builderStrategy annotation parameter. Then the generated class will not have a separate inner helper builder class and build method. The default prefix is set to set, but we can change that if we want to:

import groovy.transform.builder.Builder
import groovy.transform.builder.SimpleStrategy

@Builder(builderStrategy = SimpleStrategy, prefix = 'assign')
class Message {
    String from, to, subject, body
}

def message = new Message()
        .assignFrom('mrhaki@mrhaki.com')  // Method per property.
        .assignTo('mail@host.nl')
        .assignSubject('Sample mail')
        .assignBody('Groovy rocks!')

assert message.body == 'Groovy rocks!'
assert message.from == 'mrhaki@mrhaki.com'
assert message.subject == 'Sample mail'
assert message.to == 'mail@host.nl'

We will see other feature of the @Builder annotation in future blog posts.

Code written with Groovy 2.3.

Groovy Goodness: More Efficient Tail Recursion With TailRecursive Annotation

Since Groovy 1.8 we can use the trampoline method for a closure to get better recursive behavior for tail recursion. All closure invocations are then invoked sequentially instead of stacked, so there is no StackOverFlowError. As from Groovy 2.3 we can use this for recursive methods as well with the @TailRecursive AST transformation. If we apply the annotation to our method with tail recursion the method invocations will be sequential and not stacked, like with the closure's trampoline method.

import groovy.transform.TailRecursive

@TailRecursive
long sizeOfList(list, counter = 0) {
    if (list.size() == 0) {
        counter
    } else {
       sizeOfList(list.tail(), counter + 1) 
    }
}

// Without @TailRecursive a StackOverFlowError
// is thrown.
assert sizeOfList(1..10000) == 10000

Code written with Groovy 2.3.

April 23, 2014

Groovy Goodness: Customize ToString Creation

The @ToString AST transformation has several parameters we can define to customize the generated code for the toString method. We have already seen some of the parameters in an earlier blog post, but in new Groovy releases some extra parameters were added.

For example we can leave out the package name of the class with the parameter includePackage. If we set the value to false the package name is not included:

package com.mrhaki.blog.groovy

import groovy.transform.*

@ToString(includePackage=false /* default true */)
class Course {
    String title
    Integer maxAttendees
}

final Course course = new Course(title: 'Groovy 101', maxAttendees: 200)

assert course.toString() == 'Course(Groovy 101, 200)'

We can skip properties with null value from the toString method output with the paramater ignoreNulls:

package com.mrhaki.blog.groovy

import groovy.transform.*

@ToString(ignoreNulls=true /* default false */)
class Course {
    String title
    Integer maxAttendees
}

final Course course = new Course(title: 'Groovy 101')

assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101)'

And since Groovy 2.1 we can cache the result of toString when we know the class is immutable or at lease we know the values won't change:

package com.mrhaki.blog.groovy

import groovy.transform.*

@ToString(cache=true /* default false */)
class Course {
    String title
    Integer maxAttendees
}

Course course = new Course(title: 'Groovy 101', maxAttendees: 200)

assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101, 200)'

// Value change will not be reflected in toString().
course.title = 'Grails with REST'

assert course.toString() == 'com.mrhaki.blog.groovy.Course(Groovy 101, 200)'
assert course.title == 'Grails with REST'

Code written with Groovy 2.2.2.

Groovy Goodness: Define Compilation Customizers With Builder Syntax

Since Groovy 2.1 we can use a nice builder syntax to define customizers for a CompileConfiguration instance. We must use the static withConfig method of the class CompilerCustomizationBuilder in the package org.codehaus.groovy.control.customizers.builder. We pass a closure with the code to define and register the customizers. For all the different customizers like ImportCustomizer, SecureASTCustomizers and ASTTransformationCustomizer there is a nice compact syntax.

In the following sample we use this builder syntax to define different customizers for a CompileConfiguration instance:

package com.mrhaki.blog

import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder
import groovy.transform.*


def conf = new CompilerConfiguration()

// Define CompilerConfiguration using 
// builder syntax.
CompilerCustomizationBuilder.withConfig(conf) {
    ast(TupleConstructor)
    ast(ToString, includeNames: true, includePackage: false)
    
    imports {
        alias 'Inet', 'java.net.URL'
    }
    
    secureAst {
        methodDefinitionAllowed = false
    }
}


def shell = new GroovyShell(conf)
shell.evaluate '''
package com.mrhaki.blog

class User {
    String username, fullname
}

// TupleConstructor is added.
def user = new User('mrhaki', 'Hubert A. Klein Ikkink')

// toString() added by ToString transformation.
assert user.toString() == 'User(username:mrhaki, fullname:Hubert A. Klein Ikkink)'

// Use alias import.
def site = new Inet('http://www.mrhaki.com/')
assert site.text
'''

Code written with Groovy 2.2.2.

December 17, 2013

Groovy Goodness: Using Package Scoped Methods, Fields and Classes

Groovy uses the Java package protected scope visibility rules to turn methods and classes into public scoped variants and fields into properties. In Java package scope visibility is applied to any field, method or class that has no explicit scope set, like public, protected or private. To get the same scope in Groovy we must use the AST transformation @PackageScope to explicitly define a field, method or class to have package scope.

In the following code we want to define a simple User class with an accessor method to change the username property. Only classes in the same package as the User class must be allowed to use this method. The method may not be invoked by classes in other packages or subclasses.

package com.mrhaki.groovy.domain

import groovy.transform.*

class User {
    private String username
    
    User(final String username) {
        this.username = username
    }

    @PackageScope 
    void changeUsername(final String newUsername) {
        this.username = newUsername
    }

    String getUsername() {
        username
    }
}

If we create a new class in another package and we want to invoke the method changeUsername() we get an error if we use @CompileStatic. We can also write a Java class to use our Groovy User class and then the compiler will also give an error.

// File: App.groovy
package com.mrhaki.groovy.app

import groovy.transform.*
import com.mrhaki.groovy.domain.User

@CompileStatic
def changeUsername() {
    final User user = new User('mrhaki')
    user.changeUsername 'Hubert A. Klein Ikkink'
}

changeUsername()

If we run the script with Groovy we get an IllegalAccessError:

$ groovyc User.groovy
$ groovy App.groovy
Caught: java.lang.IllegalAccessError: tried to access method com.mrhaki.groovy.domain.User.changeUsername(Ljava/lang/String;)V from class com.mrhaki.groovy.app.App
java.lang.IllegalAccessError: tried to access method com.mrhaki.groovy.domain.User.changeUsername(Ljava/lang/String;)V from class com.mrhaki.groovy.app.App
 at com.mrhaki.groovy.app.App.changeUser(App.groovy:10)
 at com.mrhaki.groovy.app.App.run(App.groovy:13)

If we write a Java class to invoke the package scoped method we get an error when we compile the class:

package com.mrhaki.groovy.app;

import com.mrhaki.groovy.domain.User;

public class Application {
    public static void main(final String[] args) {
        final User user = new User("mrhaki");
        user.changeUsername("Hubert A. Klein Ikkink");
    }
}

The compilation error:

$ javac -cp . Application.java
Application.java:8: error: changeUsername(String) is not public in User; cannot be accessed from outside package
        user.changeUsername("Hubert A. Klein Ikkink");
            ^
1 error

The @PackageScope annotation can be used at class, field and method level. We can also add an argument to the annotation if applied at class level. We can then use the constants in groovy.transform.PackageScopeTarget to make all fields package scoped with FIELDS, all methods with METHODS and the class with CLASS.

Code written with Groovy 2.2.1.

November 19, 2013

Groovy Goodness: Cache Methods Invocations with Memoize Annotation

In Groovy we can cache closure results with memoization. In Groovy 2.2 a new @Memoize AST transformation is added, which can be used to cache plain method results. We apply the annotation to our method and the result of the method is cached if the method is invoked for the first time. If we invoke the method a second time with the same arguments then the cached result is returned.

In the following sample we want to cache the method increment(int). We use a script variable incrementChange to show when a cached method invocation takes place or a non-cached one.

import groovy.transform.*

// Script variable which is changed when increment()
// method is invoked. 
// If cached method call is invoked then the value
// of this variable will not change.
@Field boolean incrementChange = false

@Memoized 
int increment(int value) {
    incrementChange = true
    value + 1 
}

// Invoke increment with argument 10.
increment(10)

// increment is invoked so incrementChange is true.
assert incrementChange

// Set incrementChange back to false.
incrementChange = false

// Invoke increment with argument 10.
increment(10)

// Now the cached method is used and
// incrementChange is not changed.
assert !incrementChange

// Invoke increment with other argument value.
increment(11)

// increment is invoked so incrementChange is true.
assert incrementChange

Groovy Goodness: Create CopyWith Method with Immutable Annotation

For a long time we can annotate a class with the @Immutable AST transformation so only an immutable instance of a class can be created. Since Groovy 2.2 we can use the annotation parameter copyWith. If we set the value of this parameter to true the AST transformation generates a new method copyWith() in the class. The method returns a new immutable instance of the class. We can pass a map with property names and values we want to set in the newly created instance.

In the following sample code we create a new immutable class User and we use the @Immutable annotation and set the parameter copyWith to true:

import groovy.transform.Immutable

@Immutable(copyWith = true)
class User {
    String name
    String email
}

// Create immutable instance of User.
def mrhaki = new User('mrhaki', 'mrhaki@mrhaki.com')

mrhaki.with {
    assert name == 'mrhaki'
    assert email == 'mrhaki@mrhaki.com'
}

// Use new copyWith method to create a new immutable
// instance of the User class where name property
// is changed and email property is unchanged.
def hubert = mrhaki.copyWith(name: 'Hubert A. Klein Ikkink')

hubert.with {
    assert name == 'Hubert A. Klein Ikkink'
    assert email == 'mrhaki@mrhaki.com'
}

// The properties are still immutable:
try {
    hubert.email = 'new-mail@host.nl'
} catch (ReadOnlyPropertyException e) {
    assert 'Cannot set readonly property: email for class: User' == e.message
}

Code written with Groovy 2.2.

Groovy Goodness: Choose Which Delegated Methods to Use

In Groovy we can use the @Delegate annotation for some time now to automatically include methods from a delegated class into our own class. When the method is invoked on our class, it will be delegated to the correct class. Since Groovy 2.2 we can use the includes and excludes annotation parameters to define which methods of the delegated class we want to use in our own class. If any required method from the delegated class, which can also be defined in an interface, is left out when we use includes and excludes, then we get a compilation error, telling us to implement the required method from the delegated class or interface.

In the following sample we define a SimpleEvent class with a start and end property we delegate to the Date class. For the start property we don't want the after() method to be delegated, because we want to delegate it to the Date object of the end property. And for the end property we want to delegate the before() delegated method of the Date object of the start property.

@groovy.transform.ToString
class SimpleEvent {
    @Delegate(excludes=['after']) Date start
    @Delegate(excludes=['before']) Date end
    String description
}

def event = new SimpleEvent(description: 'Groovy seminar',
                            start: nextWeek, 
                            end: nextWeek + 3)

// Delegate to Date start property.
assert event.before(nextWeek + 1)
assert !event.before(nextWeek - 1)
assert !event.before(today)

// Delegate to Date end property.
assert event.after(today)        
assert event.after(nextWeek + 1)     
assert !event.after(nextWeek + 4)        


// Helper get methods:
def getToday() {
    new Date().clearTime()
}

def getNextWeek() {
    today + 7
}

Code written with Groovy 2.2.

May 30, 2013

Groovy Goodness: Customize Log Variable Name with Log AST Annotations

To add logging to a class with Groovy is easy. We apply one of the logging AST transformations and we get a variable in our class named log. We can invoke methods on the variable and the AST transformation will also automatically wrap those statement in a "if-logging-level-is-enabled" block. The transformation is even intelligent enough to do this only if Strings are added or a GString is used. If we want to use a different name than log we simply use the value parameter of the annotation. We assign the name we want to use and then we can use it in our code.

import groovy.util.logging.*

@Log(value = 'LOGGER')
class Event {
    String name
    Boolean started
    
    void start() {
        LOGGER.info "Event $name is started"
        started = true
    }
}

final Event event = new Event(name: 'gr8Conf')
event.start()
...
INFO: Event gr8Conf is started
...

Code written with Groovy 2.1.3.

May 28, 2013

Groovy Goodness: @DelegatesTo For Type Checking DSL

Groovy 2.1 introduced the @DelegatesTo annotation. With this annotation we can document a method and tell which class is responsible for executing the code we pass into the method. If we use @TypeChecked or @CompileStatic then the static type checker of the compiler will use this information to check at compile-time if the code is correct. And finally this annotation allows an IDE to give extra support like code completion.

Suppose we have the following class Reservation with the method submit(). The method accepts a closure with methods that need to be applied with the instance of the Reservation class. This is a very common pattern for writing simple DSLs in Groovy.

class Reservation {
    private Date date
    private String event
    private String attendee
    
    void date(final Date date) { this.date = date }
    void event(final String event) { this.event = event }
    void attendee(final String attendee) { this.attendee = attendee }
    
    /** Submit a reservation. 
      * @param config Configuration for reservation, invoking method class on Reservation.
      */
    static void submit(final Closure config) {
        final Reservation reservation = new Reservation()
        reservation.with config
    }

}

class Event {
    /** Use Reservation configuration DSL to submit a reservation. */
    void submitReservation() {
        Reservation.submit {
            date Date.parse('yyyyMMdd', '20130522')
            event 'Gr8Conf'
            attendee 'mrhaki'
            reserved true
        }
    }
}

final event = new Event()
event.submitReservation()

When we look at the code we might already see there is an error. In the Event.submitReservation() method we have the line reserved true, which will try to invoke the reserve() method of the Reservation class. But that method is not defined. When we run the application we get the expected error:

Exception thrown
May 28, 2013 6:58:36 AM org.codehaus.groovy.runtime.StackTraceUtils sanitize
WARNING: Sanitizing stacktrace:
groovy.lang.MissingMethodException: No signature of method: Reservation.reserved() is applicable for argument types: (java.lang.Boolean) values: [true]

To get an error for this line at compile-time we must add some annotation so the Groovy compiler can do static type checking on our code. We change the code and get the following sample:

import groovy.transform.*

class Reservation {
    private Date date
    private String event
    private String attendee
    
    void date(final Date date) { this.date = date }
    void event(final String event) { this.event = event }
    void attendee(final String attendee) { this.attendee = attendee }
    
    /** Submit a reservation. 
      * @param config Configuration for reservation, invoking method class on Reservation.
      */
    static void submit(@DelegatesTo(Reservation) final Closure config) {
        final Reservation reservation = new Reservation()
        reservation.with config
    }

}

@TypeChecked
// @CompileStatic - will also do static type checking
class Event {
    /** Use Reservation configuration DSL to submit a reservation. */
    void submitReservation() {
        Reservation.submit {
            date Date.parse('yyyyMMdd', '20130522')
            event 'Gr8Conf'
            attendee 'mrhaki'
            reserved true
        }
    }
}

final event = new Event()
event.submitReservation()

When the code is compiled we immediately get a compilation error:

1 compilation error:

[Static type checking] - Cannot find matching method Event#reserved(boolean). Please check if the declared type is right and if the method exists.
 at line: 26, column: 13

Wow, this useful! We find errors in our DSL before the code is run.

When we create this code in an IDE like IntelliJ IDEA we also get code completion in the Reservation.submit() method invocation in the Event class. The following screenshot shows code completion and a red font for reserved to indicate the compilation error.


Code written in Groovy 2.1.3