示例代码,可以在groovy 2.4.4下的GroovyConsole中轻松运行:
import groovy.transform.CompileStatic
class Echo {
public void text(String txt) {
println txt
}
}
class Test {
private Echo echo = new Echo()
@CompileStatic
public void doStuff() {
Closure c = {
echo.text('hi')
}
c()
}
}
new Test().doStuff()
它以java.lang.ClassCastException: Test$_doStuff_closure1 cannot be cast to Test
失败。
有趣的是,如果我删除@CompileStatic
注释或使成员变量非私有,它将按预期工作。
修改:提交了JIRA问题GROOVY-7558
答案 0 :(得分:2)
我认为您已经发现了一个错误。如果预期@CompileStatic
将禁止访问私有变量,那么这也应该失败
import groovy.transform.CompileStatic
class Echo {
public void text(String txt) {
println txt
}
}
@CompileStatic
class Test {
private Echo echo = new Echo()
public void doStuff() {
Closure c = {
echo.text('hi')
}
c()
}
}
new Test().doStuff()
但它没有。有些Jiras可能是同一个问题(GROOVY-6278,GROOVY-7165,GROOVY-6468),但我不确定根本原因是否相同。我要说为此开一个新的Jira。