Search code examples
file-iogroovyjunit

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


I don't understand why I am getting the following error. Any thoughts?

I am getting error:

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

This is the code producing the error at line '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 )
    }
}

I don't understand why envProp.exists() is trying to cast anything as another object. Method .exists() should just return a boolean.

Thanks


Solution

  • I had the same problem today, but in my case was:

    org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.util.List'
    

    The thing is that if your have something like this:

    public List<Foo> method(){
        methodThatReturnsTrue()
    }
    

    Because Groovy uses the last sentence's return as the method's return value, it tries to cast true to <some_not_boolean_type> and so the error you and I are getting.