5

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
  • Could you include the java source code also? Oct 10, 2019 at 7:52

1 Answer 1

5

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
4
  • Thanks, that did the trick. By the way, from your variable namings I guess that you called the method invokeMethod on an Invocable object. Is it always safe to cast engineManager.getEngineByName("nashorn") to NashornScriptEngine?
    – Ercksen
    Oct 12, 2015 at 14:25
  • 1
    @Ercksen I am not 100% sure, but the following code is safe ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); Invocable inv = (Invocable) engine; inv.invokeFunction("hello", "Scripting!"); If you have further questions, please ask a separate question so it can be useful to other users of SO Oct 12, 2015 at 14:31
  • It would be great if you could include the whole solution. If the javascript code (var Namespace={....}) is in a string called say js, then you would have to do "engine.eval(js)" or "engine.eval(reader)" if you are using a file reader. I dont see how you can eval a string literal "JSON" or "Namespace" as this is not javascript code. Contexts are not really explained in the reference docs, and havent found any useful descriptions of what they are and how to use them Oct 10, 2019 at 7:49
  • @johnlittle the example I provided works. JSON is a built-in namespace, it is a valid JS reference. I'm showing you how to call its parseString method. If the OP had already created a global called Namespace, by evaling it previously, you can access that also from the same engine Oct 10, 2019 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.