如何在 JEXL 中连接字符串和表达式

How to concatenate a String and expression in JEXL

我正在使用 JEXL http://commons.apache.org/proper/commons-jexl/ 来评估字符串。

我试过下面的代码

        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);

它正在计算表达式的错误结果。当我尝试连接两个字符串时,效果很好。当我尝试连接字符串和表达式时它不起作用。

那么,如何在 JEXL 中连接字符串和表达式?

在执行三元运算符 ?: 之前,JEXL 似乎正在执行 'some text'output 的连接。

使用您的原始表达式 'some text ' + output?'true':'false',我得到 true 的输出。我不完全确定为什么 'some text ' + false 会产生 true,但这里必须进行某种到 boolean 的隐式转换。

删除三元运算符,使用 'some text ' + output,我得到 some text false

在原始表达式中放置括号以明确表达正在发生的事情,我可以用表达式 ('some text ' + output)?'true':'false'.

复制 true 的输出

在三元运算符两边加上括号,我可以让三元运算符先运算并得到输出 some text false 表达式 'some text ' + (output?'true':'false').

这是因为三元运算符 ?: 的优先级低于 JEXL 中的 + 运算符,匹配 Java 的运算符优先级。在适当的位置添加括号会强制先执行 ?: 运算符。