Search code examples
javascriptjavanamespacesnashorn

Nashorn: Call function inside of a namespace


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?


Solution

  • 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