Tuesday, February 9, 2010

Calling Groovy closure from Java

After spending some time with Groovy alone i thought to mix Groovy code with Java. As closures seems the most weird in Groovy i tried to access a closure method from the Java class.

// Groovy code
class ClosureTest{
String firstName
String lastName

def proc(Closure closure){
closure.call(firstName, lastName)

// Groovy client
def ct = new ClosureTest()
ct.firstName = "dhaval"
ct.lastName = "nagar"
ct.proc{fn, ln -> println "$fn, $ln"}

// Java client

import groovy.lang.Closure;

class JavaClosureClient{
public static void main(String[] args){
ClosureTest ct = new ClosureTest();

ct.proc(new Closure(ct){
public Object call(Object[] argument){
System.out.println(argument[0] + ", " + argument[1]);
return null;

Well the difference shows the verbosity of the Java client compared to the Groovy one.

At my workplace we are not in a position to use Groovy extensively but with such silent integration between the two i am sure we can leverage some of the Groovy features.

No comments:

Post a Comment