-
public class TestA {
-
public static void main(String[] args) throws Exception {
-
String str = "(a >= 0 && b <= 5)";
-
ScriptEngineManager manager = new ScriptEngineManager();
-
ScriptEngine engine = manager.getEngineByName("js");
-
engine.put("a", 4);
-
engine.put("b", 5);
-
Object result = engine.eval(str);
-
System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
-
}
-
}
输出结果:
结果类型:java.lang.Boolean,计算结果:false
还可以使用 commons-jexl3 jar包
示例:
-
public static void main(String[] args){
-
String expressionString = "1+2+3";
-
-
JexlEngine jexlEngine = new JexlBuilder().create();
-
JexlExpression jexlExpression = jexlEngine.createExpression(expressionString);
-
Object evaluate = jexlExpression.evaluate(null);
-
System.out.println(evaluate);
-
}
结果: 6
示例2:
来个复杂点的
-
public static void main(String[] args){
-
// String expressionString = "1+2+3";
-
-
String expressionString = "100*10-(200+300)";
-
-
JexlEngine jexlEngine = new JexlBuilder().create();
-
JexlExpression jexlExpression = jexlEngine.createExpression(expressionString);
-
Object evaluate = jexlExpression.evaluate(null);
-
System.out.println(evaluate);
-
}
结果: 500
阅读(1639) | 评论(0) | 转发(0) |