[英]apply closure to an arbitrary object in groovy
在gradle中,您可以在某些地方以构建器样式将闭包传递给对象本身,如下所示:
// ant is a property. an object.
ant {
// do funky builder stuff
}
如何创建自己的自定义代码以将闭包应用于对象? 有没有我需要重写的方法来支持这一点?
您可以覆盖call
运算符。 Groovy允许您不要在闭包参数周围放置圆括号。
class A {
def call(Closure cl) {
print(cl())
}
}
def a = new A();
a {
"hello"
}
打印你好。
添加到海鸥提到的方式:
使用采取闭包的方法:
class MyClass {
def ant (c) {
c.call()
}
}
def m = new MyClass()
m.ant {
println "hello"
}
另一种方法是使用缺少的方法,这在采用闭包的方法名称方面具有更大的灵活性(在您的情况下为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.