Implementing Methods of a Java Interface as Instance Methods of an Object in a Script - Java Scripting

Java examples for Scripting:Bindings

Description

Implementing Methods of a Java Interface as Instance Methods of an Object in a Script

Demo 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("Interface implementation in "
          + "script is not supported.");
      return;/* w  ww. ja v  a2 s.  c  o  m*/
    }
    Invocable inv = (Invocable) engine;
    String script = "var calc = new Object(); "
        + "calc.add = function add(n1, n2) {return n1 + n2; }; "
        + "calc.subtract = function subtract(n1, n2) {return n1 - n2;};";
    engine.eval(script);
    Object calc = engine.get("calc");
    Calculator calculator = inv.getInterface(calc, Calculator.class);
    if (calculator == null) {
      System.err.println("Calculator interface " + "implementation not found.");
      return;
    }
    int result1 = calculator.add(15, 10);
    System.out.println("add(15, 10) = " + result1);
    int result2 = calculator.subtract(15, 10);
    System.out.println("subtract(15, 10) = " + result2);
  }
}
interface Calculator {
  int add(int n1, int n2);
  int subtract(int n1, int n2);
}

Related Tutorials