Java Reference
In-Depth Information
Putting Them Together
In this section, I will show you how instances of
Bindings
and their scopes,
ScriptContext
,
ScriptEngine
,
ScriptEngineManager
, and the host application work
together. The focus will be on how to manipulate the key-value pairs stored in
Bindings
in different scopes using a
ScriptEngine
and a
ScriptEngineManager
.
A
ScriptEngineManager
maintains a set of key-value pairs in a
Bindings
. It lets you
manipulate those key-value pairs using the following four methods:
•
void put(String key, Object value)
•
Object get(String key)
•
void setBindings(Bindings bindings)
Bindings getBindings()
The
put()
method adds a key-value pair to the
Bindings
. The
get()
method returns
the value for the specified key; it returns
null
if the key is not found. The
Bindings
for an
engine manager can be replaced using the
setBindings()
method. The
getBindings()
method returns the reference of the
Bindings
of the
ScriptEngineManager
.
Every
ScriptEngine
, by default, has a
ScriptContext
known as its default context.
Recall that, besides readers and writers, a
ScriptContext
has two
Bindings
: one in the
engine scope and one in the global scope. When a
ScriptEngine
is created, its engine
scope
Bindings
is empty and its global scope
Bindings
refers to the
Bindings
of the
ScriptEngineManager
that created it.
By default, all instances of the
ScriptEngine
created by a
ScriptEngineManager
share the
Bindings
of the
ScriptEngineManager
. It is possible to have multiple instances
of
ScriptEngineManager
in the same Java application. In that case, all instances of
ScriptEngine
created by the same
ScriptEngineManager
share the
Bindings
of the
ScriptEngineManager
as their global scope
Bindings
for their default contexts.
The following snippet of code creates a
ScriptEngineManager
, which is used to
create three instances of
ScriptEngine
:
•
// Create a ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
// Create three ScriptEngines using the same ScriptEngineManager
ScriptEngine engine1 = manager.getEngineByName("JavaScript");
ScriptEngine engine2 = manager.getEngineByName("JavaScript");
ScriptEngine engine3 = manager.getEngineByName("JavaScript");
Now, let's add three key-value pairs to the
Bindings
of the
ScriptEngineManager
and two key-value pairs to the engine scope
Bindings
of each
ScriptEngine
:
// Add three key-value pairs to the Bindings of the manager
manager.put("K1", "V1");
manager.put("K2", "V2");
manager.put("K3", "V3");
Search WWH ::
Custom Search