How do you invoke a method in a Nashorn CompiledScript?

旧巷老猫 提交于 2020-01-05 17:18:44

问题


I have the following code which works:

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

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

but I want to do use a pre-compiled script so I don't have to evaluate the script every time I need to run it, so I'm trying;

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

but then I'm not sure what to do with CompiledScript, how do I invoke a method? it doesn't implement anything else than eval() apparently: https://docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html


回答1:


You call the method?

Here are few examples: http://www.programcreek.com/java-api-examples/index.php?api=javax.script.CompiledScript


Example:

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");
    }
}


来源:https://stackoverflow.com/questions/32252843/re-using-a-nashorn-scriptengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!