Groovy闭包委托定义参数?

时间:2017-05-04 16:21:55

标签: groovy closures

我正在学习groovy代表

class GroovyGreeter {
    String greeting = "Default greeting"
    def printGreeting(){println "Greeting: $greeting"}
}
def myGroovyGreeter = new GroovyGreeter()
myGroovyGreeter.printGreeting() // default 
myGroovyGreeter.greeting = "My custom outer greeting"
myGroovyGreeter.printGreeting()
def greetingClosure = {
    println greeting  //equal to delegate.greeting
    println this.class
    println owner.class
    println delegate.class
    greeting = "Setting the greeting from a closure" // this is ??????
    printGreeting()
    delegate.greeting = "setting the greeting from delegate.greeting..."
    printGreeting()
}
greetingClosure.delegate = myGroovyGreeter
greetingClosure() // This works as `greeting` is a property of the delegate

os:windows10 terminal:cywin groovy:2.4.10 jvm 1.8

Greeting: Default greeting
Greeting: My custom outer greeting
My custom outer greeting
class closureuda
class closureuda
class GroovyGreeter
Greeting: My custom outer greeting
Greeting: setting the greeting from delegate.greeting...

我很困惑为什么闭包中的问候语的变量不会出现在 delegate.greeting

当我对代码进行decopile并发现 - greeting 被定义为局部变量时:

private static /* synthetic */ CallSiteArray $createCallSiteArray() {
    String[] strArr = new String[1]; // this  is greeting definition
    strArr[0] = "printGreeting";
    return new CallSiteArray(closureuda$_run_closure1.class, strArr);
}

1 个答案:

答案 0 :(得分:0)

默认情况下,Groovy会在转到委托之前查看闭包的范围,所以为了在委托中设置你想要的东西,这可能不是你想要的......幸运的是,你可以改变解决策略: / p>

greetingClosure.resolveStrategy = Closure.DELEGATE_FIRST

在行

之后立即放置
greetingClosure.delegate = myGroovyGreeter

你应该得到你期望的输出