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?



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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.