Java Reference
In-Depth Information
To execute a compiled script, you need to call one of the following
eval()
methods
of the
CompiledScript
class:
•
Object eval() throws ScriptException
•
Object eval(Bindings bindings) throws ScriptException
Object eval(ScriptContext context) throws ScriptException
The
eval()
method without any arguments uses the default script context of the
script engine to execute the compiled script. The other two versions work the same
as the
eval()
method of the
ScriptEngine
interface when you pass a
Bindings
or a
ScriptContext
to them.
•
■
When you evaluate scripts using the
eval()
method of the
CompiledScript
class,
changes in the state of the engine made during the execution of the compiled script may be
visible in the subsequent execution of the scripts by the engine.
Tip
Listing 5-8 shows how to compile a script and execute it. It executes the same
compiled script twice with different parameters.
Listing 5-8.
Using Compiled Scripts
// CompilableTest .java
package com.jdojo.script;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class CompilableTest {
public static void main(String[] args) {
// Get the Nashorn engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
if (!(engine instanceof Compilable)) {
System.out.println(
"Script compilation not supported.");
return;
}
Search WWH ::
Custom Search