Java ScriptEngine load inline Javascript function

Description

Java ScriptEngine load 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 {/*  ww  w. j  a va  2s.c  o  m*/
         nashorn.eval("function add(a,b){"//
               + "  var v = a + b;"//
               + "return v; }");//
         nashorn.eval("print('sum: '+ add(16,32))");
      } catch (ScriptException ex) {
         ex.printStackTrace();
         ;
      }
   }
}



PreviousNext

Related