按名称查找Groovy Closure

moe*_*eTi 0 groovy

我尝试在Groovy中调用动态闭包,现在我被卡住了.我有名字,但我不知道如何用call()方法引用它

这是我想要实现的一个小例子:

def fooClos = { println foo }
def barClos = { println bar}
def c = new Random().nextInt() % 2 == 0 ? "foo" : "bar"
"${c}Clos".call()
Run Code Online (Sandbox Code Playgroud)

所以最后一行应该打印foobar

我也试过了

this."${c}Clos".call()
Run Code Online (Sandbox Code Playgroud)

this.&"${c}Clos".call()
Run Code Online (Sandbox Code Playgroud)

没有任何成功.
那么有人可以帮助我如何正确的参考看起来?我可以解决我的问题,但我仍然想知道它是如何完成的.

tim*_*tes 5

它适用def于你不使用你的闭包(所以他们进入脚本的绑定)

fooClos = { println 'foo' }
barClos = { println 'bar' }
def c = new Random().nextInt() % 2 == 0 ? "foo" : "bar"
"${c}Clos"()
Run Code Online (Sandbox Code Playgroud)

如果使用@Field注释标记它们,它也会起作用,因此它们会被添加为生成的Script类的字段:

import groovy.transform.*

@Field def fooClos = { println 'foo' }
@Field def barClos = { println 'bar' }
def c = new Random().nextInt() % 2 == 0 ? "foo" : "bar"
"${c}Clos"()
Run Code Online (Sandbox Code Playgroud)

多一点解释

你有效的原始方式有效编译:

public java.lang.Object run() {
    java.lang.Object fooClos = { 
        return this.println('foo')
    }
    java.lang.Object barClos = { 
        return this.println('bar')
    }
    c = new java.util.Random().nextInt() % 2 == 0 ? 'foo' : 'bar'
    return this."$cClos"()
}
Run Code Online (Sandbox Code Playgroud)

所以fooClos并且barClosrun方法中的局部变量.然后它试图打电话this.fooClosthis.barClos显然失败了