Scripting in Java Tutorial - Compiled Scripts








A script engine allows to compile a script in the form of Java classes and then execute it repeatedly.

The following code checks if a script engine implements the Compilable interface:

import javax.script.Compilable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
//from   w w  w  . ja  v  a  2  s .c  o  m
public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    if (engine instanceof Compilable) {
      System.out.println("Script compilation is supported.");
    } else {
      System.out.println("Script compilation is not supported.");
    }

  }
}

The code above generates the following result.





Example

The Compilable interface contains two methods:

CompiledScript compile(String script) throws ScriptException
CompiledScript compile(Reader script) throws ScriptException

To execute a compiled script, call one of the following eval() methods from the CompiledScript class.

Object eval() throws ScriptException
Object eval(Bindings bindings) throws ScriptException
Object eval(ScriptContext context) throws ScriptException

The following code shows how to compile a script and execute it. It executes the same compiled script twice with different parameters.

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
//from   w w  w .j av a 2  s.  c  o  m
public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    if (!(engine instanceof Compilable)) {
      System.out.println("Script compilation not supported.");
      return;
    }
    Compilable comp = (Compilable) engine;
    
    CompiledScript cScript = comp.compile("print(n1 + n2)");

    Bindings scriptParams = engine.createBindings();
    scriptParams.put("n1", 2);
    scriptParams.put("n2", 3);
    cScript.eval(scriptParams);

    scriptParams.put("n1", 9);
    scriptParams.put("n2", 7);
    cScript.eval(scriptParams);
  }
}

The code above generates the following result.