【发布时间】:2013-07-25 10:59:39
【问题描述】:
这行得通:
def myClosure = { println 'Hello world!' }
'myClosure'()
这不起作用:
def myClosure = { println 'Hello world!' }
String test = 'myClosure'
test()
为什么,有没有办法?
【问题讨论】:
这行得通:
def myClosure = { println 'Hello world!' }
'myClosure'()
这不起作用:
def myClosure = { println 'Hello world!' }
String test = 'myClosure'
test()
为什么,有没有办法?
【问题讨论】:
有
test()
解析器会将其评估为对 test 闭包/方法的调用,而不首先将其评估为变量(否则您无法调用任何具有同名变量的方法)
请尝试:
myClosure = { println 'Hello world!' }
String test = 'myClosure'
"$test"()
class Test {
def myClosure = { println "Hello World" }
void run( String closureName ) {
"$closureName"()
}
static main( args ) {
new Test().run( 'myClosure' )
}
}
class Test {
def myClosure = { println "Hello World" }
def run = { String closureName ->
"$closureName"()
}
static main( args ) {
new Test().run( 'myClosure' )
}
}
【讨论】:
$test 的闭包)。当您在纯脚本中运行它时,您是否像我在上面的代码中那样从 Closure 定义中删除了 def?
def 似乎确实使它工作......在一个简单的脚本中。但是我只设置了其中一个来拥有一个独立的示例。实际上,所有这些都存在于class 中。我发现将def 放入class 的结果很糟糕。
Test 类中,我的run() 本身就是一个闭包(而不是一个方法,就像你在这里一样)。这似乎不起作用。
run 是一个闭包,它似乎也可以工作......