Java 支持JavaScript脚本计算

Java支持了JavaScript脚本的执行计算能力:

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

public class JsExecutor {

    private static ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");

    public static void main(String[] args) {
        /*
         *  采用js计算,思路就是将要计算的逻辑,拼接为一个js的函数,
         *  然后通过scriptEngine执行这个函数,得到结果
         */
        StringBuffer func = new StringBuffer();
        func.append("function func() {");
        func.append("    var a = 10;");
        func.append("    return a>1;");
        func.append("}");

        try {
            //编译js脚本
            scriptEngine.eval(func.toString());
            
            //计算编译后的js中的函数
            Invocable inv = (Invocable) scriptEngine;
            boolean result = (boolean) inv.invokeFunction("func");
            
            System.out.println("result : " + result);
        } catch (ScriptException e) {
            System.out.println("error occurs in script");
        } catch (NoSuchMethodException e) {
            System.out.println("no such method in script");
        }
    }

}

 

posted @ 2016-10-10 21:38  烈日1990  阅读(265)  评论(0编辑  收藏  举报