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'andoutputbefore the ternary operator?:is performed.With your original expression,
'some text ' + output?'true':'false', I get an output oftrue. I'm not entirely sure why'some text ' + falseyieldstrue, but there must be some kind of implicit conversion tobooleangoing on here.Removing the ternary operator, using
'some text ' + output, I getsome text false.Placing parentheses in the original expression to explicitly express what's happening, I can duplicate the output of
truewith 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 falsewith 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.