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()
以匹配{{ 1}}“属性”。如果我不使用revision
变量,则对revision
的调用不会调用此bean行为。
任何有关文档的见解或链接都将受到赞赏!
答案 0 :(得分:1)
可用于控制分辨率顺序的Groovy闭包have a resolveStrategy
property。默认策略是从“拥有”对象中查找属性,并且只有在那里找不到它才能使用委托。我相信将其设置为DELEGATE_FIRST
会得到您期望的行为。