在groovy中,从闭包中引用私有成员变量是合法的吗?

jck*_*111 10 groovy

可以在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()
Run Code Online (Sandbox Code Playgroud)

它失败了java.lang.ClassCastException: Test$_doStuff_closure1 cannot be cast to Test.

有趣的是,如果我删除@CompileStatic注释或使成员变量非私有,它按预期工作.

编辑:提交JIRA问题GROOVY-7558

Kee*_*gan 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()
Run Code Online (Sandbox Code Playgroud)

但事实并非如此。有一些 Jira 可能存在相同的问题(GROOVY-6278GROOVY-7165GROOVY-6468),但我不确定根本原因是否相同。我想说,为此打开一个新的 Jira。