Java Invocable call Javascript function and pass parameters

Description

Java Invocable call Javascript function and pass parameters

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("nashorn");

      // JavaScript code in a String
      String gallonsFunction = "function add(a, b){var v = a +b; "
              + " return v; } ";
      try {//from w  w  w.j a  v a 2s  .  c o m
          // evaluate script
          engine.eval(gallonsFunction);
          double width = 16.0;
          double length = 32.0;
          Invocable inv = (Invocable) engine;
          double returnValue = (double) inv.invokeFunction("add",
                                        new Double[]{width,length});
          System.out.println("The returned value:" + returnValue);
          
          // Invoke a script
          //engine.eval("load('main.js')");
          //Invocable inv2 = (Invocable) engine;
          //String returnValue2 = (String) inv2.invokeFunction("returnName", new String[]{"Nashorn"});
          //System.out.println("The returned value:" + returnValue2);

      } catch (ScriptException | NoSuchMethodException ex) {
          ex.printStackTrace();
      }

   }
}



PreviousNext

Related