java 执行运算字符串中的js代码并且返回结果

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ExpressTest {

    public static void test1() throws ScriptException {
        String str = "(a >= 0 && a <= 5)";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("a", 4);
        Object result = engine.eval(str);
        System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
    }
    
    public static void test2() throws ScriptException {
        String str = "43*(2 + 1.4)+2*32/(3-2.1)";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        Object result = engine.eval(str);
        System.out.println("结果类型:" + result.getClass().getName() + ",计算结果:" + result);
    }
    
    public static void main(String[] args) throws ScriptException {
        test1();
        test2();
    }
}

jdk1.6中可以直接这样用
jdk1.5中需要以下jar:commons-logging-1.1.1.jar, js.jar, bsf-all-3.0.jar

转载至:https://www.cnblogs.com/tsql/p/11201594.html

上一篇:Go之组件学习-channel(concurrency篇)


下一篇:Go快速入门1