是否可以将Groovy闭包的范围设置为调用方法?请参阅以下示例代码:
class TestClass {
def testMethod() {
def i = 42
def closure = testClosure()
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.delegate = this.&testMethod
closure() // Should print 42.
}
def testMethod2() {
def i = 43
def closure = testClosure()
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.delegate = this.&testMethod2
closure() // Should print 43.
}
def testClosure = {
println i // I get a MissingPropertyException: No such property i
}
}
def test = new TestClass()
test.testMethod()
test.testMethod2()
答案 0 :(得分:2)
不,但您可以将i
移动到与闭包相同的范围:
class TestClass {
def i
def testMethod() {
i = 42
testClosure() // Should print 42.
}
def testMethod2() {
i = 43
testClosure() // Should print 43.
}
def testClosure = {
println i // I get a MissingPropertyException: No such property i
}
}
def test = new TestClass()
test.testMethod()
test.testMethod2()