CHAPTER 9 SCRIPTING AND JSR 223 175
CHAPTER 9 SCRIPTING AND JSR 223 177 The Compilable Interface Typically, scripting languages are interpreted. What this means is that each time the scripting source is read, it is evaluated before executing. To optimize execution time, you can compile some of that source such that future executions are faster. That is where the Compilable interface comes into play. If a specific scripting engine also implements Compilable, then you can precompile scripts before execution. The compilation process involves the compile() method of Compilable, and returns a CompiledScript upon success. As shown in Listing 9-4, execution of the compiled script is now done with the eval() method of CompiledScript, instead of the ScriptEngine. Listing 9-4. Working with Compilable Scripts import javax.script.*; import java.io.*; public class CompileTest { public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(”javascript”); engine.put(”counter”, 0); if (engine instanceof Compilable) { Compilable compEngine = (Compilable)engine; try { CompiledScript script = compEngine.compile( “function count() { ” + ” counter = counter +1; ” + ” return counter; ” + “}; count();”); Console console = System.console(); console.printf(”Counter: %s%n”, script.eval()); console.printf(”Counter: %s%n”, script.eval()); console.printf(”Counter: %s%n”, script.eval()); } catch (ScriptException e) { System.err.println(e); } } else { System.err.println(”Engine can’t compile code”); } } }
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services