Gnarly Custom Groovy Closures

In a previous post I went over Groovy closures. In this post I will show how you can extend a Java class so as to use it to construct a closure in a Groovy script. I’ll start by defining a plain old Java class with an array of data.

public class Sentence {
    public String[] getWords() {
        return new String[]{"Hello", "World"};
    }
}

You will need to write a Sentence helper class that will iterate over the words and call the Groovy closure. Here is a sample implementation:

public class SentenceClosure {
    public static void each(Sentence s, Closure c) {
        String words = s.getWords();
        for(int i=0; i < words.length; i++) {
            c.call(words[i]);
        }
    }
}

Once you compile the above classes and add them to your classpath you can write a Groovy script such as:

def sentence = new Sentence();
use(SentenceClosure.class) {
    sentence.each {
        println " -> ${it}";
    }
}

At this point you will notice that in the Groovy script it looks like the class Sentence defines an each method but that method is actually implemented in the SentenceClosure class. The SentenceClosure helper class allows you to separate closure specific code from you business class.

Technorati Tags: , , ,