How do you invoke a method in a Nashorn CompiledScript?

后端 未结 1 976
忘了有多久
忘了有多久 2020-12-11 05:11

I have the following code which works:

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

jsEng         


        
相关标签:
1条回答
  • 2020-12-11 05:52

    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");
        }
    }
    
    0 讨论(0)
提交回复
热议问题