用表达式语言比较字符串和布尔值(Comparing string and boolean in Expression language)
我有这种行为,我真的不明白
${someVar} ${someVar.class.name} ${someVar == 'error'}输出
false java.lang.Boolean true 它如何被排除? 为了首先测试这两种“事物”是否具有相同类型,然后它们的值是否相同,编写测试的正确方法是什么?I have this behaviour I do not really understand
${someVar} ${someVar.class.name} ${someVar == 'error'}outputs
false java.lang.Boolean true How can it be exlpained? 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?最满意答案
这是EL规范中定义的语言行为:
A {==,!=,eq,ne} B
其他规则消失了 如果A或B为布尔值,则强制A和B都为布尔值,应用运算符将A强制为布尔值
如果A为空或“”,则返回false 否则,如果A是布尔值,则返回A. 否则, 如果A是一个字符串,并且Boolean.valueOf(A)不会引发异常,则返回它 否则,错误
所以,字符串文字通过Boolean.valueOf("error")被强制为一个布尔值,它返回false 。
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 operatorCoerce 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.
更多推荐
发布评论