Nashorn: Call function inside of a namespace

六月ゝ 毕业季﹏ 提交于 2019-12-10 16:48:18

问题


I have evaluated the following script using the NashornScriptEngine:

var Namespace = {
    test: function()
    {
        return "It works";
    }
}

Now I want to call the function test.

When using the method invokeFunction of the nashorn engine, the following exception is thrown:

java.lang.NoSuchMethodException: No such function Namespace.test

How is it possible to call this function?


回答1:


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).

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


来源:https://stackoverflow.com/questions/33082818/nashorn-call-function-inside-of-a-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!