【发布时间】:2016-08-21 18:54:51
【问题描述】:
我目前正在编写 gradle 构建脚本。什么是委托对象以及它们何时使用?
class GroovyGreeter {
String greeting = "Default greeting"
def printGreeting(){println "Greeting: $greeting"}
}
def myGroovyGreeter = new GroovyGreeter()
myGroovyGreeter.printGreeting()
myGroovyGreeter.greeting = "My custom greeting"
myGroovyGreeter.printGreeting()
/*
The last Groovy feature we'll cover is that closures can have a delegate
object. Any variables or methods referenced in the closure that don't have a
local definition are then evaluated against the closure's delegate. Let's make
a closure that will access the property and method of our GroovyGreeter class.
*/
def greetingClosure = {
greeting = "Setting the greeting from a closure"
printGreeting()
}
//greetingClosure() // This doesn't work, because `greeting` isn't defined
greetingClosure.delegate = myGroovyGreeter
greetingClosure() // This works as `greeting` is a property of the delegate
请帮帮我。
【问题讨论】: