Search code examples
javanashornscriptengine

How can I access a static-method only class via ScriptEngine?


I have a class Foo that has only one static method (of note), called bar(). I need to access bar() via a runtime script (in this case Javascript).

final ScriptEngineManager factory;
factory = new ScriptEngineManager();

factory.put("foo", new Foo());

The above works, but it seems a bit odd to me. Specifically I don't want to create a new Foo. Foo is public, so there must be a way to let the script factory know about it, without instantiating a new object. I have tried factory.put("foo", Foo.class); but that didn't work. I also tried specifying the package in the Javascript code, eg.

package.Foo.bar();

but that didn't work either.

Q: Is there a way to access a class' static methods from an embedded script, without binding an instance of that class to the engine?


Solution

  • You should write the Packages keyword before the complete path of the class.
    Example:

    javax.script.ScriptEngine engine = 
            new javax.script.ScriptEngineManager().getEngineByName("JavaScript");
    engine.eval("Packages.yourpackages.Foo.bar()");
    

    Documention links in OpenJDK Wiki: https://wiki.openjdk.java.net/display/Nashorn/Nashorn+Documentation

    Here is something about the Packages object: http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html