如何调用Nashorn CompiledScript中的方法?

时间:2015-08-27 14:15:48

标签: javascript java nashorn scriptengine

我有以下代码可以使用:

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
jsEngine.eval("some script");

jsEngine.invokeMethod(jsEngine.eval("foo"), "bar");

但我想使用预编译的脚本,所以每次我需要运行它时都不必评估脚本,所以我正在尝试;

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn");
CompiledScript compiledJS = jsEngine.compile("some script");

但是我不知道如何处理CompiledScript,我该如何调用方法?它显然没有实现除eval()以外的任何东西:https://docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html

1 个答案:

答案 0 :(得分:4)

你打电话给方法吗?

以下是一些示例:http://www.programcreek.com/java-api-examples/index.php?api=javax.script.CompiledScript

示例:

import java.util.*;
import javax.script.*;

public class TestBindings {
    public static void main(String args[]) throws Exception {
        String script = "function doSomething() {var d = date}";
        ScriptEngine engine =  new ScriptEngineManager().getEngineByName("JavaScript");
        Compilable compilingEngine = (Compilable) engine;
        CompiledScript cscript = compilingEngine.compile(script);

        //Bindings bindings = cscript.getEngine().createBindings();
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        for(Map.Entry me : bindings.entrySet()) {
            System.out.printf("%s: %s\n",me.getKey(),String.valueOf(me.getValue()));
        }
        bindings.put("date", new Date());
        //cscript.eval();
        cscript.eval(bindings);

        Invocable invocable = (Invocable) cscript.getEngine();
        invocable.invokeFunction("doSomething");
    }
}