Nashorn:名称空间内的调用函数 [英] Nashorn: Call function inside of a namespace
问题描述
我已经使用NashornScriptEngine
评估了以下脚本:
I have evaluated the following script using the NashornScriptEngine
:
var Namespace = {
test: function()
{
return "It works";
}
}
现在我要调用函数test
.
Now I want to call the function test
.
使用nashorn引擎的方法invokeFunction
时,将引发以下异常:
When using the method invokeFunction
of the nashorn engine, the following exception is thrown:
java.lang.NoSuchMethodException: No such function Namespace.test
如何调用此函数?
推荐答案
您正在尝试访问名为window["Namespace.test"]
而不是window.Namespace.Test
的全局函数.您首先需要获得对Namespace
的引用,然后可以调用
You are trying to access a global function called window["Namespace.test"]
, not window.Namespace.Test
. You first need to get a reference to Namespace
, then you can call invocable.invokeMethod
specifying Namespace
as its context (this
).
例如,要调用JSON.parse()
,可以使用以下命令:
For example, to call JSON.parse()
, you can use the following:
Object json = engine.eval("JSON"); // Or "Namespace" in your case
Object data = invocable.invokeMethod(json, "parse", contactJson); //"test" for the case you mention
这篇关于Nashorn:名称空间内的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!