Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 677
Eric Francis Avatar asked Jun 12 '13 14:06

Eric Francis


2 Answers

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.

like image 163
Alfergon Avatar answered Nov 15 '22 03:11

Alfergon


For the sake of completeness I need to say that I got a similar message:

Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.util.List'

When I invoked:

final List<String> reportedChangedFiles = linesOfChangedFiles.removeAll([null])

I was expecting removeAll() to return a new collection but I forgot that it modifies the current collection and returns a boolean instead. So it was as easy as:

linesOfChangedFiles.removeAll([null])
like image 30
Igor Rodriguez Avatar answered Nov 15 '22 05:11

Igor Rodriguez