Scripting in Java Tutorial - Call Javascript function








The following code shows how to call Javascript functions from Java.

First, it defines four functions in the Javascript file and saves it to the 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;

Then, loads the script using the eval() function and get the Object representing the functions.

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

Finally, get the function by name and pass in the parameters.

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);




Example

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/*w w  w . j a  v  a 2s .  c om*/
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);
  }
}

The code above generates the following result.

Here is the source code for 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;