Java Reference
In-Depth Information
msg = Hello
year = 1969
year = null
params contains year = false
You will not use a
Bindings
by itself. Often, you will use it to pass parameters from
Java code to a script engine. The
ScriptEngine
interface contains a
createBindings()
method that returns an instance of the
Bindings
interface. This method gives a script
engine a chance to return an instance of the specialized implementation of the
Bindings
interface. You can use this method, as shown:
// Get the Nashorn engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Do not instantiate the SimpleBindings class, use the
// createBindings() method of the engine instead
Bindings params = engine.createBindings();
// Work with params as usual
Scope
Let's move to the next term, which is scope. A scope is used for a
Bindings
. The scope of a
Bindings
determines the visibility of its key-value pairs. You can have multiple
Bindings
occurring in multiple scopes. However, one
Bindings
may occur only in one scope. How
do you specify the scope for a
Bindings
? I will cover this shortly.
Using the scope for a
Bindings
lets you define parameter variables for script engines
in a hierarchical order. If a variable name is searched in an engine state, the
Bindings
with a higher precedence is searched first, followed by
Bindings
with lower precedence.
The first found value of the variable is returned.
The Java Scripting API defines two scopes. They are defined as two
int
constants in
the
ScriptContext
interface. They are:
•
ScriptContext.ENGINE_SCOPE
ScriptContext.GLOBAL_SCOPE
The engine scope has higher precedence than the global scope. If you add two
key-value pairs with the same key to two
Bindings
(one in engine scope and one in global
scope), the key-value pair in the engine scope will be used whenever a variable with the
same name as the key has to be resolved.
Understanding the role of the scope for a
Bindings
is so important that I will
run through another analogy to explain it. Think about a Java class that has two sets
of variables: one set contains all instance variables in the class and another contains
all local variables in a method. These two sets of variables with their values are two
Bindings
. The type of variables in a
Bindings
defines the scope. Just for the sake of this
•
Search WWH ::
Custom Search