例如:
@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()
将字符串强制转换为数值,并且仅作为最后一种情况使用字符串连接对操作数进行操作。具体来说:
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"
关于java - 如何在jexl中连接两个数字字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22447971/