简体   繁体   English

Groovy闭包委托定义参数?

[英]Groovy closure delegate define parameter?

I'm learning groovy delegate 我正在学习时髦的代表

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 os:windows10终端: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...

I'm confused about why the variable of greeting in the closure is not equeal to the delegate.greeting 我很困惑为什么闭包中的问候变量不会对delegate.greeting产生影响

When i decopile the code and found that —— the greeting is define as a local variable: 当我对代码进行decopile并发现 - 问候语被定义为局部变量:

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);
}

Groovy by default will look at the closure's scope before going to the delegate, so for setting things that you want in the delegate, this is probably not what you want... Luckily, you can change the resolve strategy with: 默认情况下,Groovy会在转到委托之前查看闭包的范围,因此,为了在委托中设置您想要的东西,这可能不是您想要的...幸运的是,您可以通过以下方式更改解析策略:

greetingClosure.resolveStrategy = Closure.DELEGATE_FIRST

Put this immediately after the line 在行之后立即放置

greetingClosure.delegate = myGroovyGreeter

and you should get the output you were expecting 你应该得到你期望的输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM