简体   繁体   中英

apply closure to an arbitrary object in groovy

In gradle there are places where you can pass a closure to an object itself in a builder style like so:

// ant is a property. an object.
ant {
    // do funky builder stuff
}

How can you create your own custom code to apply closures to objects? is there a method that i need to override in order to support this?

You could override the call operator. Groovy allows you to not place round braces around the closure argument.

class A {
  def call(Closure cl) {
    print(cl())
  }
}
def a = new A();
a {
    "hello"
}

Prints hello.

Adding to the way seagull mentioned:

Using a method that takes a closure:

class MyClass { 
  def ant (c) {
    c.call()
  }
}

def m = new MyClass()
m.ant { 
  println "hello"
}

Other one, using method missing, which gives more flexibility in terms of name of the method that takes a closure ( ant in your case):

class A {
     def methodMissing(String name, args) {
        if (name == "ant") {
            // do somehting with closure
            args.first().call()
        }
    }
}

def a = new A()

a.ant { println "hello"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM