Invoking a Function Written in Nashorn JavaScript - Java Scripting

Java examples for Scripting:Run Script

Description

Invoking a Function Written in Nashorn JavaScript

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) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    if (!(engine instanceof Invocable)) {
      System.out.println("Invoking procedures is not supported.");
      return;/*from  w  w w  . jav  a 2s. c o m*/
    }
    Invocable inv = (Invocable)engine;
    try {
      String script = "function add(n1, n2) { return n1 + n2; }";
      engine.eval(script);
      Object result1 = inv.invokeFunction("add", 30, 40);
      System.out.println("Result1 = " + result1);
      Object result2 = inv.invokeFunction("add", 10, 20);
      System.out.println("Result2 = " + result2);
    }
    catch (ScriptException | NoSuchMethodException e) {
      e.printStackTrace();
    }
  }
}

Result


Related Tutorials