A Bindings is a set of key-value pairs and the keys must be nonempty, non-null Strings.
Java Bindings is an instance of the Bindings interface.
SimpleBindings class is an implementation of the Bindings interface.
Bindings interface inherits from the Map<String,Object>
interface.
Bindings is a Map with a restriction that its keys must be nonempty, non-null strings.
import javax.script.Bindings; import javax.script.SimpleBindings; //from w ww . j av a 2 s . com public class Main { public static void main(String[] args) { Bindings params = new SimpleBindings(); params.put("stringKey", "Hello"); params.put("valueKey", 2015); Object msg = params.get("stringKey"); Object year = params.get("valueKey"); System.out.println("stringKey" + msg); System.out.println("valueKey = " + year); params.remove("valueKey"); year = params.get("valueKey"); boolean containsYear = params.containsKey("valueKey"); System.out.println("valueKey = " + year); System.out.println("params contains year = " + containsYear); } }
The code above generates the following result.
To pass parameters from Java code to a script engine, use a createBindings() method from ScriptEngine interface which returns an instance of the Bindings interface.
import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /* w w w . j av a 2s .co m*/ public class Main { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); Bindings params = engine.createBindings(); params.put("stringKey", "Hello"); params.put("valueKey", 2015); Object msg = params.get("stringKey"); Object year = params.get("valueKey"); System.out.println("stringKey" + msg); System.out.println("valueKey = " + year); params.remove("valueKey"); year = params.get("valueKey"); boolean containsYear = params.containsKey("valueKey"); System.out.println("valueKey = " + year); System.out.println("params contains year = " + containsYear); } }
The code above generates the following result.
Typically, a key in the engine scope Bindings represents a script variable.
The following table lists reserved keys with special meanings.
Key | Constant | Meaning |
---|---|---|
"javax.script.argv" | ScriptEngine.ARGV | pass an array of Object |
"javax.script.engine" | ScriptEngine.ENGINE | name of the script engine |
"javax.script.engine_version" | ScriptEngine.ENGINE_VERSION | version of the script engine |
"javax.script.filename" | ScriptEngine.FILENAME | pass the name of the file |
"javax.script.language" | ScriptEngine.LANGUAGE | The name of the language |
"javax.script.language_version" | ScriptEngine.LANGUAGE_VERSION | version of the scripting language supported by the engine |
"javax.script.name" | ScriptEngine.NAME | The short name of the scripting language |