Implementing a Java Interface Using Top-Level Functions in Script - Java Scripting

Java examples for Scripting:Bindings

Description

Implementing a Java Interface Using Top-Level Functions in Script

Demo 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.");
      return;//  ww w.  j  ava 2  s .c  o m
    }
    Invocable inv = (Invocable) engine;
    String script = "function add(n1, n2) { return n1 + n2; } "
        + "function subtract(n1, n2) { return n1 - n2; }";

    engine.eval(script);
    Calculator calc = inv.getInterface(Calculator.class);
    if (calc == null) {
      System.err.println("Calculator interface " + "implementation not found.");
      return;
    }

    int result1 = calc.add(15, 10);
    System.out.println("add(15, 10) = " + result1);

    int result2 = calc.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