Nashorn:在命名空间内调用函数
Nashorn: Call function inside of a namespace
我使用 NashornScriptEngine
评估了以下脚本:
var Namespace = {
test: function()
{
return "It works";
}
}
现在我想调用函数test
。
使用nashorn引擎的方法invokeFunction
时,抛出如下异常:
java.lang.NoSuchMethodException: No such function Namespace.test
如何调用这个函数?
您正在尝试访问名为 window["Namespace.test"]
的全局函数,而不是 window.Namespace.Test
。您首先需要获得对 Namespace
的引用,然后您可以调用 invocable.invokeMethod
并指定 Namespace
作为其上下文 (this
)。
例如,要调用JSON.parse()
,您可以使用以下内容:
Object json = engine.eval("JSON"); // Or "Namespace" in your case
Object data = invocable.invokeMethod(json, "parse", contactJson); //"test" for the case you mention
我使用 NashornScriptEngine
评估了以下脚本:
var Namespace = {
test: function()
{
return "It works";
}
}
现在我想调用函数test
。
使用nashorn引擎的方法invokeFunction
时,抛出如下异常:
java.lang.NoSuchMethodException: No such function Namespace.test
如何调用这个函数?
您正在尝试访问名为 window["Namespace.test"]
的全局函数,而不是 window.Namespace.Test
。您首先需要获得对 Namespace
的引用,然后您可以调用 invocable.invokeMethod
并指定 Namespace
作为其上下文 (this
)。
例如,要调用JSON.parse()
,您可以使用以下内容:
Object json = engine.eval("JSON"); // Or "Namespace" in your case
Object data = invocable.invokeMethod(json, "parse", contactJson); //"test" for the case you mention