groovy中的.delegate是什么意思?

我发现这个代码片段:

def say = {println m} say.delegate = [m:2] say() 

这明显地打印2.它是如何工作的? 哪里可以find关于.delegate文档? Google引导我进入了“Delegate Transformation”页面,它根本没有提到.delegate

闭包的委托是一个对象,用于parsing在闭包本身内部无法parsing的引用。 如果你的例子是这样写的:

 def say = { def m = 'hello' println m } say.delegate = [m:2] say() 

它打印“hello”,因为m可以在closures中解决。 但是,当封闭内没有定义m时,

 def say = { println m } say.delegate = [m:2] say() 

delegate用于parsing引用,在这种情况下delegate是映射m到2的映射。

closures的三个属性,是这个,所有者和代表 ,总的来说代表是所有者

 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