[英]How to connect two numeric string in jexl?
例如:
@Test
public void test2() {
JexlEngine jexl = new JexlEngine();
jexl.setLenient(false);
jexl.setSilent(false);
JexlContext jc = new MapContext();
Expression exp = jexl.createExpression("\"1\"+\"1\"");
System.out.println(exp.evaluate(jc));
}
实际结果是:
2
我的预期结果是:
"11"
请告诉我上面的例子有什么问题。 我怎样才能得到预期的结果。
谢谢!
看看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()
字符串JexlArithmetic.add()
为数值,并且仅作为最后一种情况使用字符串连接来操作操作数。 特别:
409 } catch (java.lang.NumberFormatException nfe) {
410 // Well, use strings!
411 return toString(left).concat(toString(right));
412 }
JexlArithmetic
的子类在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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.