2

I know that I can create Java objects and call methods on them using the code like:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
            engine.eval("var SomeJavaClass = " + "Java.type('somepackage.SomeJavaClass');" +
"var x = new SomeJavaClass();" +
"x.doSomething();"

But is it possible to call methods on already existing Java objects using nashorn?

0

1 Answer 1

2

Yes. Use ScriptEngineManager.getBindings().put(String name, Object value) to put existing objects in the engine scope.

Example:

import javax.script.*;

public class NashornVariables {
    public static class SomeJavaClass {
        public void doSomething() {
            System.out.println("I did something!");
        }
    }

    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        manager.getBindings().put("x", new SomeJavaClass());
        ScriptEngine engine = manager.getEngineByName("nashorn");
        engine.eval(
            "x.doSomething();"
        );
    }
}

Result:

$ javac NashornVariables.java; java NashornVariables
I did something!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.