Scripting in Java Tutorial - Scripting Java interface

Implementing Java Interfaces in Scripts

The Java Scripting API allows us to implement Java interfaces in a scripting language.


Suppose we would like to implement the following Java interface in Javascript.

public interface Calculator {
   double add (double n1, double n2);

The Contents of the cal.js File, save it under c:/Java_dev/cal.js

function add(n1, n2) {
  n1 + n2;

Call the Java interface implemented in Javascript from the Java code.

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

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("Interface implementation in script"
          + "is not supported.");
    Invocable inv = (Invocable) engine;
    String scriptPath = "c:/Java_Dev/cal.js";
    engine.eval("load('" + scriptPath + "')");
    Calculator calc = inv.getInterface(Calculator.class);
    if (calc == null) {
      System.err.println("Calculator interface "
          + "implementation not found.");
    double x = 2.0;
    double y = 1.0;
    double addResult = calc.add(x, y);