Java Reference
In-Depth Information
You can also retrieve the value of a key in a specific scope. The following snippet of
code retrieves values for the key “ year ” from the engine scope and the global scope:
// Assigns 1969 to engineScopeYear and 1982 to globalScopeYear
int engineScopeYear = (Integer)ctx.getAttribute("year", ScriptContext.
ENGINE_SCOPE);
int globalScopeYear = (Integer)ctx.getAttribute("year", ScriptContext.
GLOBAL_SCOPE);
the Java scripting api defines only two scopes: engine and global. a subinterface of
the ScriptContext interface may define additional scopes. the getScopes() method of the
ScriptContext interface returns a list of supported scopes as a List<Integer> . note that
a scope is represented as an integer. the two constants, ENGINE_SCOPE and GLOBAL_SCOPE
in the ScriptContext interface, are assigned values 100 and 200, respectively. When a key
is searched in multiple Bindings occurring in multiple scopes, the scope with the lower
integer value is searched first. Because the value 100 for the engine scope is lower than the
value 200 for the global scope, the engine scope is searched for a key first when you do not
specify the scope.
Tip
Listing 3-2 shows how to work with an instance of a class implementing the
ScriptContext interface. Note that you do not use a ScriptContext in your application
by itself. It is used by script engines during script execution. Most often, you manipulate a
ScriptContext indirectly through a ScriptEngine and a ScriptEngineManager , which is
discussed in detail in the next section.
Listing 3-2. Using an Instance of the ScriptContext Interface
// ScriptContextTest.java
package com.jdojo.script;
import java.util.List;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;
import static javax.script.ScriptContext.ENGINE_SCOPE;
import static javax.script.ScriptContext.GLOBAL_SCOPE;
 
 
Search WWH ::




Custom Search