.delegate在groovy中意味着什么?

时间:2011-11-14 11:33:23

标签: groovy

我找到了这段代码:

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

显然是打印2.它是如何工作的?哪里可以找到有关.delegate的文档?谷歌引导我进入代表转换页面,完全没有提到.delegate

2 个答案:

答案 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