Source From Here
Preface
Groovy supports closures and they are very useful when we create Groovy applications. For example we can pass closures as arguments to methods to execute them. We can create closures ourselves, but we can also convert a method to a closure with the .& operator. And we can use the converted method just like a normal closure. Because Groovy can use Java objects we can also convert a Java method into a closure.
How-To
Let's start with a simple Java class:
With the following script we use this Java class and convert the
javaSays method to a closure:
If we run this script we get the following output:
Supplement
* [ User Guide ] Closure
* [ In Action ] Working with closures - The case for closures
* [ In Action ] Working with closures - Declaring closures
Preface
Groovy supports closures and they are very useful when we create Groovy applications. For example we can pass closures as arguments to methods to execute them. We can create closures ourselves, but we can also convert a method to a closure with the .& operator. And we can use the converted method just like a normal closure. Because Groovy can use Java objects we can also convert a Java method into a closure.
How-To
Let's start with a simple Java class:
- public class JavaObject {
- public static void javaSays(final String s) {
- System.out.println("Java says: Hello " + s + "!");
- }
- }
- // Simple list with names.
- def names = ['groovy', 'grails', 'mrhaki']
- // Simple closure.
- names.each { println 'Normal closure says: Hello ' + it + '!' }
- // Groovy method to convert to closure.
- def groovySays(s) {
- printf("Groovy says: Hello ${s}!\n")
- }
- // Use .& syntax to convert method to closure.
- names.each(this.&groovySays)
- // Convert Java method to closure and use it.
- def javaSays = JavaObject.&javaSays
- names.each javaSays
Supplement
* [ User Guide ] Closure
* [ In Action ] Working with closures - The case for closures
* [ In Action ] Working with closures - Declaring closures
沒有留言:
張貼留言