How do you call a method in Nashorn CompiledScript?

I have the following code that works:

ScriptEngine jsEngine = ScriptEngineManager.new().getEngineByName("nashorn"); jsEngine.eval("some script"); jsEngine.invokeMethod(jsEngine.eval("foo"), "bar"); 

but I want to use a precompiled script, so I don’t need to evaluate the script every time I need to run it, so I try;

 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 call a method? it does not implement anything other than eval (), apparently: https://docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html

+6
source share
1 answer

Are you calling a method?

Here are some 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"); } } 
+4
source

All Articles