Java Reference
In-Depth Information
discussion, I will define two scopes: instance scope and local scope. When a method is
executed, a variable name is looked up in the local scope Bindings first because the local
variables take precedence over instance variables. If a variable name is not found in the
local scope Bindings , it is looked up in the instance scope Bindings . When a script is
executed, Bindings and their scopes play a similar role.
Defining the Script Context
A script engine executes a script in a context. You can think of the context as the
environment in which a script is executed. A Java host application provides two things
to a script engine: a script and the context in which the script needs to be executed.
An instance of the ScriptContext interface represents the context for a script. The
SimpleScriptContext class is an implementation of the ScriptContext interface.
A script context consists of four components:
Bindings , in which each Bindings is associated with a
different scope
A set of
Reader that is used by the script engine to read inputs
A
Writer that is used by the script engine to write outputs
A
Writer that is used by the script engine to write error
An error
outputs
The set of Bindings in a context is used to pass parameters to the script. A reader
and writers in a context control input source and output destinations of the script,
respectively. For example, by setting a file writer as a writer, you can send all outputs from
a script to a file.
Each script engine maintains a default script context, which it uses to execute scripts.
So far, you have executed several scripts without providing script contexts. In those
cases, script engines were using their default script contexts to execute scripts. In this
section, I will cover how to use an instance of the ScriptContext interface by itself. In the
next section, I will cover how an instance of the ScriptContext interface is passed to a
ScriptEngine during script execution.
You can create an instance of the ScriptContext interface using the
SimpleScriptContext class, like so:
// Create a script context
ScriptContext ctx = new SimpleScriptContext();
An instance of the SimpleScriptContext class maintains two instances of Bindings :
one for engine scope and one for global scope. The Bindings in the engine scope is
created when you create the instance of the SimpleScriptContext . To work with the
global scope Bindings , you will need to create an instance of the Bindings interface.
 
Search WWH ::




Custom Search