【问题标题】:What does .delegate mean in groovy?.delegate 在 groovy 中是什么意思?
【发布时间】:2011-11-14 11:33:22
【问题描述】:

我找到了这段代码sn-p:

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

这显然打印了 2。它是如何工作的?在哪里可以找到有关 .delegate 的文档? Google 将我带到了完全没有提及 .delegate 的委托转换页面。

【问题讨论】:

标签: groovy


【解决方案1】:

闭包的委托是一个对象,用于解析无法在闭包主体内解析的引用。如果你的例子是这样写的:

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 是一个将 m 映射到 2 的 Map

【讨论】:

  • 为闭包提供默认参数的便捷方式:def say = { def m = m ?: 'hello'; println m }
  • @thenaglecode 我想你的意思是这个def say = { def m = it ?: 'hello'; println m }
【解决方案2】:

闭包的三个属性,分别是this、owner、delegate,一般delegate都设置为owner

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

【讨论】:

  • 默认情况下可能是所有者,但驱动 Groovy DSL 的是您可以将委托重新分配给任何对象
猜你喜欢
  • 2011-05-11
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 2011-08-12
  • 2017-06-11
相关资源
最近更新 更多