Friday, September 30, 2011

From Java Methods to Groovy Closures



Groovy supports nice conversion of Java methods into a Groovy closure.

The Groovy way:

// Groovy way to get a method closure (MethodClosure)
def setter = joo.&setName
setter('JJ')

def getter = joo.&getName
assert getter() == 'JJ'


The underneath implementation:

// If there is a method overloading,
// the first method that has the most arguments is used.

// Create a method closure (MethodClosure)
def setter1 = InvokerHelper.getMethodPointer(joo, 'setName')
setter1('Jerry')
assert joo.name == 'Jerry'


// Method closure based on a static method
def staticMethod = InvokerHelper.getMethodPointer(JavaBean, 'bark')
assert staticMethod() == 'Wolf!'


And of course, you can always roll up your sleeves and code a nice closure class.

No comments: