使用nashorn从JavaScript引用现有的Java对象

时间:2018-11-25 12:00:40

标签: javascript java nashorn

我知道我可以使用以下代码创建Java对象并在其上调用方法:

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

但是可以使用nashorn在已经存在的Java对象上调用方法吗?

1 个答案:

答案 0 :(得分:2)

是的。使用ScriptEngineManager.getBindings().put(String name, Object value)将现有对象放入引擎范围。

示例:

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();"
        );
    }
}

结果:

$ javac NashornVariables.java; java NashornVariables
I did something!