Ercksen Ercksen - 10 months ago 73
Java Question

Nashorn: Call function inside of a namespace

I have evaluated the following script using the


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

Now I want to call the function

When using the method
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?


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