1

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?

rgettman
  • 176,041
  • 30
  • 275
  • 357
abhinav
  • 527
  • 3
  • 11
  • 24
  • What do you mean by "not working"? Are you getting an error? Incorrect result? What version of JEXL are you using? I don't get a ParseException with 2.1.1. – rgettman Jun 16 '15 at 21:54
  • I am using version 2.1.1 . I am getting wrong result – abhinav Jun 16 '15 at 22:38
  • @rgettman , I am not getting ParseException now. But it is evaluating the expression to a wrong result. – abhinav Jun 16 '15 at 22:40

1 Answers1

3

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357