Comparing string and boolean in Expression language

Paolo picture Paolo · Nov 17, 2011 · Viewed 11k times · Source

I have this behaviour I do not really understand

${someVar}
${someVar.class.name}      
${someVar == 'error'}

outputs

false
java.lang.Boolean
true
  1. How can it be exlpained?
  2. What it the correct way to write the test in order to first test if the two 'things' have the same type and then if their value is the same?

Answer

McDowell picture McDowell · Nov 17, 2011

This is the behaviour of the language as defined in the EL specification:

A {==,!=,eq,ne} B

  • other rules elided
  • If A or B is Boolean coerce both A and B to Boolean, apply operator

Coerce A to Boolean

  • If A is null or "", return false
  • Otherwise, if A is a Boolean, return A
  • Otherwise, if A is a String, and Boolean.valueOf(A) does not throw an exception, return it
  • Otherwise, error

So, the string literal is coerced to a boolean via Boolean.valueOf("error") which returns false.