简体   繁体   English

将闭包应用于groovy中的任意对象

[英]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: 在gradle中,您可以在某些地方以构建器样式将闭包传递给对象本身,如下所示:

// 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. 您可以覆盖call运算符。 Groovy allows you to not place round braces around the closure argument. Groovy允许您不要在闭包参数周围放置圆括号。

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): 另一种方法是使用缺少的方法,这在采用闭包的方法名称方面具有更大的灵活性(在您的情况下为ant ):

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"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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