第一种方式, 使用SpringEL表达式.
public static void main(String[] args) {
SpelExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("(1 + 1) * 2 / 0");
Integer value = expression.getValue(Integer.class);
System.out.println(value);
}
第二种方式, 使用exp4j, 这是一个用于数学公式计算的jar包, 适用于金融领域.
public static void main(String[] args) {
Expression e = new ExpressionBuilder("(x + x) * y")
.variables("x", "y")
.build()
.setVariable("x", 1)
.setVariable("y", 2);
double result = e.evaluate();
System.out.println(result);
}
更多的例子参考如下:
exp4j - Download exp4j (objecthunter.net)
exp4j/ExpressionBuilderTest.java at master · fasseg/exp4j · GitHub