Java ScriptEngine get return value from inline Javascript function

Description

Java ScriptEngine get return value from inline Javascript function

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

public class Main {

   public static void main(String[] args) {
      ScriptEngineManager sem = new ScriptEngineManager();
      ScriptEngine nashorn = sem.getEngineByName("nashorn");
      try {// w w w .  j  a v a2 s.  com
          nashorn.eval("function add(a, b){"//
                + "var v = a +b;"//
                  + "return v; }");
          Integer d = (Integer) nashorn.eval("add(16,32);");
          System.out.println("Sum: " + d);
      } catch (ScriptException ex) {
          ex.printStackTrace();
      }
   }
}



PreviousNext

Related