Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
Ercksen Avatar asked Oct 12 '15 13:10

Ercksen


1 Answers

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
like image 116
Juan Mendes Avatar answered Sep 30 '22 06:09

Juan Mendes