0 Replies Latest reply on Nov 10, 2016 11:41 AM by jdalecki-JavaNet

    What is the difference between eval and compile methods



      I am pretty new to Java Script in javax.script package. I am just wondering and scratching my head off to understand the difference between
      Compilable.compile(String script) and ScriptEngine.eval(String script).
      Let’s assume I get somehow the “engine” object:
          ScriptEngineManager factory = new ScriptEngineManager();
          ScriptEngine engine = factory.getEngineByName("JavaScript");
      Let’s say I have a script string like this: string = “function raiseAlarm()
          var now = new java.util.Date();
          print("major " + now);
      If I evaluate it and call it this way:
      Invocable inv = (Invocable) engine;
      1. inv.invokeFunction("raiseAlarm”);
      … Well it works (no compilation involved)
      However if I compile it and then not evaluate it and then try to call a method (“raiseAlarm”) I get an exception java.lang.NoSuchMethodException: No such function raiseAlarm. (Something like this):
      Compilable compEngine = (Compilable) engine;
      script = compEngine.compile(string);
      Invocable inv = (Invocable) engine;
      1. inv.invokeFunction("raiseAlarm”);
      So my question is what is the point of compiling that script string if I still have to evaluate it to get a result without an error? What have I achieved by compiling it?


      Kind Regards,