看看http://svn.apache.org/viewvc/commons/proper/jexl/tags/COMMONS_JEXL_2_1_1/src/main/java/org/apache/commons/jexl2/JexlArithmetic.java?view=markup(第373行),JexlArithmetic.add()
将字符串强制转换为数值,并且仅在最后一种情况下使用字符串连接对操作数进行操作。具体来说:
409 } catch (java.lang.NumberFormatException nfe) {
410 // Well, use strings!
411 return toString(left).concat(toString(right));
412 }
一个子类在JexlArithmetic
这里是合适的。我们可以给出一个表现出你想要的行为的new JexlEngine()
。这是一个可能的子类:
public class NoStringCoercionArithmetic extends JexlArithmetic {
public NoStringCoercionArithmetic(boolean lenient) {
super(lenient);
}
public NoStringCoercionArithmetic() {
this(false);
}
@Override
public Object add(Object left, Object right) {
if (left instanceof String || right instanceof String) {
return left.toString() + right.toString();
}
else {
return super.add(left, right);
}
}
}
在测试中:
JexlEngine jexl = new JexlEngine(null, new NoStringCoercionArithmetic(), null, null);
jexl.setLenient(false);
jexl.setStrict(true);
JexlContext jc = new MapContext();
Expression exp = jexl.createExpression("\"1\"+\"1\"");
System.out.println(exp.evaluate(jc)); // expected result "11"