Groovy 似乎有一些与“Groovy Beans”和闭包相关的非常不愉快的行为,这些行为可能导致它在某些情况下屏蔽局部变量。
这是已知的行为吗?是否有一些文档详细说明了这些内容?我浪费了很多时间试图弄清楚什么不起作用......
考虑以下代码:
class TestClass {
def doIt(Closure closure) {
closure.setDelegate(this)
closure.call()
}
def getRevision() {
return "testclass revision"
}
}
def testIt() {
def revision = "testit revision"
println "1: " + revision + " (expect: testit)"
TestClass tester = new TestClass()
tester.doIt {
println "2: " + getRevision() + " (expect: testclass)"
}
println "3: " + revision + " (expect: testit)"
tester.doIt {
println "4: " + revision + " (expect: testit)"
revision = getRevision()
println "5: " + revision + " (expect: testclass)"
println "6: ${getRevision()} (expect: testclass)"
println "7: " + getRevision() + " (expect: testclass)"
}
// expect to have been set to testclass value in previous closure
println "8: " + revision + " (expect: testclass)"
tester.doIt {
println "9: ${getRevision()} (expect: testclass)"
println "10: " + getRevision() + " (expect: testclass)"
}
println "11: " + revision + " (expect: testclass)"
}
testIt()
运行此代码会产生以下输出:
1: testit revision (expect: testit)
2: testclass revision (expect: testclass)
3: testit revision (expect: testit)
4: testit revision (expect: testit)
5: testit revision (expect: testclass)
6: testit revision (expect: testclass)
7: testit revision (expect: testclass)
8: testit revision (expect: testclass)
9: testclass revision (expect: testclass)
10: testclass revision (expect: testclass)
11: testit revision (expect: testclass)
我的主要问题是 5/6/7。似乎只是revision
在闭包中使用局部变量“隐藏”getRevision()
了委托中的方法,并将其替换为自动生成的 bean 样式getRevision()
以匹配revision
“属性”。如果我不使用该revision
变量,则调用getRevision()
不会调用此 bean 行为。
任何见解或文档链接将不胜感激!