Creating and Passing Groovy Closures from Java

Groovy has supported closures from day one, but Java is still toying with the idea. Surprisingly, creating closures in Java and invoking Groovy methods that take them is quite simple thanks to Groovy’s dynamic nature. Whereas Java insists that we send methods instances of the proper type, Groovy is quite friendly and is happy that we use its features.

Upon close examination, we’ll discover that when Groovy invokes a closure it simply uses a special method named call. To create a closure in Java, we need only a class that has this method. If the Groovy code will pass arguments to the closure, we must make sure our call method accepts those arguments as parameters.

It’s very simple to create closures ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.