Java Reference
In-Depth Information
Using Compiled Scripts
A script engine may allow compiling a script and executing it repeatedly. Executing
compiled scripts may increase the performance of an application. A script engine may
compile and store scripts in the form of Java classes, Java class files, or in a language-
specific form.
Not all script engines are required to support script compilation. Script engines that
support script compilation must implement the Compilable interface. Nashorn engine
supports script compilation. The following snippet of code checks if a script engine
implements the Compilable interface:
// Get the script engine reference
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("YOUR_ENGINE_NAME");
if (engine instanceof Compilable) {
System.out.println("Script compilation is supported.");
}
else {
System.out.println("Script compilation is not supported.");
}
Once you know that a script engine implements the Compilable interface, you can
cast its reference to a Compilable type, like so:
// Cast the engine reference to the Compilable type
Compilable comp = (Compilable)engine;
The Compilable interface contains two methods:
CompiledScript compile(String script) throws
ScriptException
CompiledScript compile(Reader script) throws
ScriptException
The two versions of the method differ only in the type of the source of the script. The
first version accepts the script as a String and the second one as a Reader .
The compile() method returns an object of the CompiledScript class.
CompiledScript is an abstract class. The provider of the script engine provides the
concrete implementation of this class. A CompiledScript is associated with the
ScriptEngine that creates it. The getEngine() method of the CompiledScript class
returns the reference of the ScriptEngine to which it is associated.
 
Search WWH ::




Custom Search