Executing compiled script

In the previous posts under “Java Scripting”, we used ScriptEngine eval method to execute scripts stored in a string variable or file.

The ScriptEngine’s eval methods takes the script compiles to intermediate code and execute it immediately.

If we have a script which has to be executed repeatedly, then instead of compiling and executing it everytime, we can compile the script to intermediate code once and run it repeatedly. This will improve the performance also.

This post explains how to achived this. The above requirement can be achieved using
1) Compilable interface
2) CompiledScript interface

The Compilable interface is used by the script engines who implement the above requirement. Compiling to intermediate code and store it for later execution.

An instance of CompiledScript class stores the compiled script.

Main Class


package package1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Demo3 {
    public static void main(String[] args) throws FileNotFoundException, IOException, ScriptException {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        File file = new File("test.js");
        try(FileReader fr = new FileReader(file);) {
            Compilable compilable = (Compilable)scriptEngine;
            CompiledScript compiledScript = compilable.compile(fr);
            compiledScript.eval();
        }
    }
}

test.js


print("This is hello from test.js");

Explanation

In the above code we cast the ScriptEngine to Compilable interface
Compilable compilable = (Compilable)scriptEngine;

The we compile the script using the “compile” method as shown below
CompiledScript compiledScript = compilable.compile(fr);

The compile method returns an instance of “CompiledScript”.

Then we can eval the script anytime we want using the eval method as shown below
compiledScript.eval();

Leave a Reply