[英]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);
它将表达式评估为错误的结果。 当我尝试连接两个String时,效果很好。 当我尝试连接字符串和表达式时,它不起作用。
那么,如何在JEXL中连接字符串和表达式?
看起来JEXL正在执行'some text'
和output
的串联,然后执行三元运算符?:
。
使用您的原始表达式'some text ' + output?'true':'false'
,我得到的输出为true
。 我不完全确定为什么'some text ' + false
产生true
,但是这里必须进行某种隐式转换为boolean
。
删除三元运算符,使用'some text ' + output
,我得到some text false
。
将括号放在原始表达式中以明确表示正在发生的事情,我可以将true
的输出与表达式('some text ' + output)?'true':'false'
复制。
将括号放在三元运算符的周围,我可以让三元运算符首先进行运算,并使用表达式'some text ' + (output?'true':'false')
来使输出的some text false
。
这是因为三元运算符?:
优先级低于JEXL中的+
运算符,与Java的运算符优先级匹配。 在适当的位置添加括号会强制首先执行?:
运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.