我找到了这段代码:
def say = {println m}
say.delegate = [m:2]
say()
显然是打印2.它是如何工作的?哪里可以找到有关.delegate
的文档?谷歌引导我进入代表转换页面,完全没有提到.delegate
。
答案 0 :(得分:58)
闭包的委托是一个对象,用于解析在闭包体本身内无法解析的引用。如果您的示例是这样写的:
def say = {
def m = 'hello'
println m
}
say.delegate = [m:2]
say()
它打印'hello',因为m
可以在闭包内解析。但是,如果未在闭包中定义m
,
def say = {
println m
}
say.delegate = [m:2]
say()
delegate
用于解析引用,在这种情况下,delegate
是将Map
映射为2的m
。
答案 1 :(得分:12)
关闭的三个属性是这个,所有者和代理,一般委托设置为所有者
def testClosure(closure) {
closure()
}
testClosure() {
println "this is " + this + ", super:" + this.getClass().superclass.name
println "owner is " + owner + ", super:" + owner.getClass().superclass.name
println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name
testClosure() {
println "this is " + this + ", super:" + this.getClass().superclass.name
println "owner is " + owner + ", super:" + owner.getClass().superclass.name
println "delegate is " + delegate + ", super:" + delegate.getClass().superclass.name
}
}
打印
this is ConsoleScript0@11d20d3, super:groovy.lang.Script
owner is ConsoleScript0@11d20d3, super:groovy.lang.Script
delegate is ConsoleScript0@11d20d3, super:groovy.lang.Script
this is ConsoleScript0@11d20d3, super:groovy.lang.Script
owner is ConsoleScript0$_run_closure1@caea19, super:groovy.lang.Closure
delegate is ConsoleScript0$_run_closure1@caea19, super:groovy.lang.Closure