如何调用Nashorn CompiledScript中的方法? [英] How do you invoke a method in a Nashorn CompiledScript?
本文介绍了如何调用Nashorn CompiledScript中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码可用:
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");
但是我不知道如何处理CompiledScript,我该如何调用方法?除了eval()之外,它没有实现任何其他功能: https://docs.oracle.com/javase/8/docs/api/javax/script/CompiledScript.html
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
推荐答案
你打电话给方法吗?
这里有几个例子: 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");
}
}
这篇关于如何调用Nashorn CompiledScript中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文