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