faeli.me

Java 调用 Javascript 代码

JavaScript d:/tmp/calculator.js

var calculator = new Object();

calculator.add = function (n1, n2) {n1 + n2};
calculator.subtract = function (n1, n2) {n1 - n2};
calculator.multiply = function (n1, n2) {n1 * n2};
calculator.divide = function (n1, n2) {n1 / n2};
function test(a, b) { if (a === 'Number') return 1; else return b};

Java Code

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

public class Main {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        if (!(engine instanceof Invocable)) {
            System.out.println("Invoking methods is not supported.");
            return;
        }
        Invocable inv = (Invocable) engine;
        String scriptPath = "d:/tmp/calculator.js";

        engine.eval("load('" + scriptPath + "')");

        Object calculator = engine.get("calculator");

        int x = 3;
        int y = 4;
        Object addResult = inv.invokeMethod(calculator, "add", x, y);
        Object subResult = inv.invokeMethod(calculator, "subtract", x, y);
        Object mulResult = inv.invokeMethod(calculator, "multiply", x, y);
        Object divResult = inv.invokeMethod(calculator, "divide", x, y);
        Object testResult = inv.invokeFunction("test", "a", "a not number");

        System.out.println(addResult);
        System.out.println(subResult);
        System.out.println(mulResult);
        System.out.println(divResult);
        System.out.println(testResult);
    }
}

结果:

7.0
-1.0
12.0
0.75
a not number