以下代码显示了如何从Java调用Javascript函数。
首先,它定义了Javascript文件中的四个函数并保存它到c:/Java_Dev/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;
然后,使用eval()函数加载脚本并获取表示函数的Object。
String scriptPath = "c:/Java_Dev/calculator.js";
engine.eval("load("" + scriptPath + "")");
Object calculator = engine.get("calculator");
最后,通过名称获取函数并传递参数。
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);
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 = "c:/Java_Dev/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);
System.out.println(addResult);
System.out.println(subResult);
System.out.println(mulResult);
System.out.println(divResult);
}
}
上面的代码生成以下结果。
这里是c:/Java_Dev/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;
© 著作权归作者所有