在Gradle中,您可以将闭包以如下所示的构建器样式传递给对象本身:
// ant is a property. an object.ant { // do funky builder stuff}
// ant is a property. an object.
ant {
// do funky builder stuff
}
如何创建自己的定制代码来将闭包应用于对象?是否有需要重写的方法才能支持此操作?
svdrlsy41#
您可以覆盖call运算符。Groovy允许您不用大括号将闭包参数括起来。
call
class A { def call(Closure cl) { print(cl()) }}def a = new A();a { "hello"}
class A {
def call(Closure cl) {
print(cl())
def a = new A();
a {
"hello"
打个招呼。
v09wglhw2#
加上海鸥提到的方式:
使用接受闭包的方法:
class MyClass { def ant (c) { c.call() }}def m = new MyClass()m.ant { println "hello"}
class MyClass {
def ant (c) {
c.call()
def m = new MyClass()
m.ant {
println "hello"
另一种是使用方法缺失,这在接受闭包的方法(在本例中为ant)的名称方面提供了更大的灵活性:
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"}
def methodMissing(String name, args) {
if (name == "ant") {
// do somehting with closure
args.first().call()
def a = new A()
a.ant { println "hello"}
2条答案
按热度按时间svdrlsy41#
您可以覆盖
call
运算符。Groovy允许您不用大括号将闭包参数括起来。打个招呼。
v09wglhw2#
加上海鸥提到的方式:
使用接受闭包的方法:
另一种是使用方法缺失,这在接受闭包的方法(在本例中为
ant
)的名称方面提供了更大的灵活性: