I am using JEXL http://commons.apache.org/proper/commons-jexl/ to evaluate Strings.
I tried the following code
String jexlExp = "'some text ' + output?'true':'false'";
JexlEngine jexl = new JexlEngine();
Expression e = jexl.createExpression(jexlExp);
JexlContext jc = new MapContext();
jc.set("output", false);
Object x = e.evaluate(jc);
System.out.println(x);
It is evaluating the expression to a wrong result. When I try to concat two Strings it works well. It is not working when I try to concat a string and expression.
So, how do I concatenate a string and expression in JEXL?
It appears that JEXL is performing the concatenation of 'some text'
and output
before the ternary operator ?:
is performed.
With your original expression, 'some text ' + output?'true':'false'
, I get an output of true
. I'm not entirely sure why 'some text ' + false
yields true
, but there must be some kind of implicit conversion to boolean
going on here.
Removing the ternary operator, using 'some text ' + output
, I get some text false
.
Placing parentheses in the original expression to explicitly express what's happening, I can duplicate the output of true
with the expression ('some text ' + output)?'true':'false'
.
Placing parentheses around the ternary operator, I can get the ternary operator to operate first and get the output some text false
with the expression 'some text ' + (output?'true':'false')
.
This occurs because the ternary operator ?:
has lower precedence than the +
operator in JEXL, matching Java's operator precedence. Adding parentheses in the proper place force the execution of the ?:
operator first.