Groovy:无法将类'java.lang.Boolean'的对象'true'强制转换为类'java.io.File'

Eri*_*cis 4 file-io groovy junit

我不明白为什么我收到以下错误.有什么想法吗?

我收到错误:

Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.io.File'

这是在'if(envProp.exists()...'行生成错误的代码:

static private File envProp = new File('env.properties')
static private File envPropBak = new File('env.properties.bak')

@BeforeClass
static void beforeAll() {
    if (envProp.exists()) {
        envPropBak.write( envProp.text )
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么envProp.exists()要把任何东西作为另一个对象.方法.exists()应该只返回一个boolean.

谢谢

Alf*_*gon 6

我今天遇到了同样的问题,但在我的情况下是:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.util.List'
Run Code Online (Sandbox Code Playgroud)

问题是如果你有这样的事情:

public List<Foo> method(){
    methodThatReturnsTrue()
}
Run Code Online (Sandbox Code Playgroud)

因为Groovy使用最后一个句子的返回值作为方法的返回值,所以它会尝试将true转换为<some_not_boolean_type>,因此你和我得到的错误.