当我评估带有或不带有绑定(bind)的 nashorn 脚本时,有一个奇怪的区别:没有绑定(bind),调用函数没有问题,但使用绑定(bind),则找不到函数。这是一个例子:
public class SimpleNashornTester {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");
Compilable jsCompilable = (Compilable) jsEngine;
Invocable jsInvocable = (Invocable) jsEngine;
ScriptContext scriptCtxt = new SimpleScriptContext();
Bindings engineScope = scriptCtxt.getBindings(ScriptContext.ENGINE_SCOPE);
CompiledScript jsScript = jsCompilable.compile("function definition() {print(\"Hello\")}");
jsScript.eval(engineScope); // no error with jsScript.eval() !
jsInvocable.invokeFunction("definition", new Object[] {});
}
}
这会产生错误:
Exception in thread "main" java.lang.NoSuchMethodException: No such function definition
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:204)
在脚本评估中如果没有参数engineScope,就会找到并调用该函数。有人能解释一下这种差异吗?如何使用绑定(bind)而不出现错误?
最佳答案
您正在使用新的 ScriptContext 及其关联的 ENGINE_SCOPE
绑定(bind)来编译脚本。 invokeFunction
/invokeMethod
使用默认的 ScriptContext(及其关联的 ENGINE_SCOPE
绑定(bind))来搜索函数。每个不同的 ENGINE_SCOPE
绑定(bind)都与其自己的 ECMAScript 全局对象(以及它自己的 ECMAScript 全局对象)相关联。
所以,你可以通过以下方式修复你的程序
在调用之前将默认上下文更改为新上下文:
// change the default ScriptContext jsEngine.setContext(scriptCtxt); jsInvocable.invokeFunction("definition", new Object[] {});
对已编译的脚本也使用默认的 ScriptContext。如:
ScriptContext scriptCtxt = jsEngine.getContext(); // new SimpleScriptContext();
关于javascript - 当使用绑定(bind)进行 eval 时,Nashorn 找不到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923659/