Java 調(diào)用Javascript函數(shù)

2018-03-18 14:01 更新

Java腳本教程 - Java調(diào)用Javascript函數(shù)


以下代碼顯示了如何從Java調(diào)用Javascript函數(shù)。

首先,它定義了Javascript文件中的四個函數(shù)并保存它到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()函數(shù)加載腳本并獲取表示函數(shù)的Object。

String scriptPath = "c:/Java_Dev/calculator.js";
engine.eval("load("" + scriptPath + "")");
Object calculator = engine.get("calculator");

最后,通過名稱獲取函數(shù)并傳遞參數(shù)。

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;


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號