我使用NashornScriptEngine
评估了以下脚本:
var Namespace = {
test: function()
{
return "It works";
}
}
现在我想调用函数test
。
使用nashorn引擎的invokeFunction
方法时,会抛出以下异常:
java.lang.NoSuchMethodException: No such function Namespace.test
如何调用此功能?
答案 0 :(得分:4)
您正在尝试访问名为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