Java Reference
In-Depth Information
■
if you are familiar with the
java.util.Map
interface, it is easy to understand
Bindings
.
the
Bindings
interface inherits from the
Map<String,Object>
interface. therefore, a
Bindings
is simply a
Map
with a restriction that its keys must be nonempty, non-null strings.
Tip
Listing 3-1 shows how to use a
Bindings
. It creates an instance of
SimpleBindings
,
adds some key-value pairs to it, retrieves the values of the keys, removes a key-value pair,
etc. The
get()
method of the
Bindings
interface returns
null
if the key does not exist or
the key exists and its value is
null
. If you want to test if a key exists, you need to use its
contains()
method.
Listing 3-1.
Using Bindings Objects
// BindingsTest.java
package com.jdojo.script;
import javax.script.Bindings;
import javax.script.SimpleBindings;
public class BindingsTest {
public static void main(String[] args) {
// Create a Bindings instance
Bindings params = new SimpleBindings();
// Add some key-value pairs
params.put("msg", "Hello");
params.put("year", 1969);
// Get values
Object msg = params.get("msg");
Object year = params.get("year");
System.out.println("msg = " + msg);
System.out.println("year = " + year);
// Remove year from Bindings
params.remove("year");
year = params.get("year");
boolean containsYear = params.containsKey("year");
System.out.println("year = " + year);
System.out.println("params contains year = " + containsYear);
}
}
Search WWH ::
Custom Search