Java 脚本引擎


Java中可以使用Nashorn Javascript引擎运行Javascript代码。


Java中调用JS代码

下面是Java中调用JS代码的例子:

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JavaCallJs {
    public static void main(String[] args) {
        try {
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
            engine.eval("function sum(a, b) { return a + b; }");
            Invocable invocable = (Invocable) engine;

            Object result = invocable.invokeFunction("sum", 1, 2);
            System.out.println(result);    // 3.0
            System.out.println(result.getClass());    // class java.lang.Double

            Object result2 = engine.eval("sum(1, 2);");
            System.out.println(result2);    // 3.0
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}


JS中调用Java代码

下面是JS中调用Java代码的例子:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class JsCallJava {
    public static String hello(String name) {
        return "hello, " + name;
    }

    public static void main(String[] args) {
        try {
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
            StringBuilder js = new StringBuilder();
            js.append("var javaClass = Java.type('JsCallJava');");
            js.append("var result = javaClass.hello('dog');");
            js.append("print(result);");
            engine.eval(js.toString());        // hello, dog
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}