Forum Stats

  • 3,724,396 Users
  • 2,244,746 Discussions
  • 7,850,991 Comments

Discussions

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

What is the difference between eval and compile methods

Hi,

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:
engine.eval(string);
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,
Janusz

Answers

  • nihitthakkar
    nihitthakkar Member Posts: 104 Red Ribbon

    In the compile mode any number of statements can be compiled into bytecode that implicitly always returns None. whereas in 'eval' mode it a single expression into bytecode is compiled that returns the value of that expression.

Sign In or Register to comment.