Previous | Next | Trail Map | The Basics | Naming Operations

Adding, Overwriting, and Removing a Binding

The Context interface contains methods for adding, overwriting, and removing a binding in a context.

Adding a Binding

The Context.bind()(in the API reference documentation) method is used to add a binding to a context. It accepts as arguments the name of the object, and the object to be bound:
// Create object to be bound
Fruit fruit = new Fruit("orange");

// Perform bind
ctx.bind("favorite", fruit);
This example creates an object of class Fruit and binds it to the name "favorite" in the context ctx. If you were to subsequently look up the name "favorite" in ctx, you would get the fruit object. Note that to compile the Fruit class, you need the FruitFactory class.

If you run this example twice, the second attempt will fail with a NameAlreadyBoundException(in the API reference documentation) because the name "favorite" is already bound. For the second attempt to succeed, you will have to use rebind()(in the API reference documentation).

Overwriting a Binding

The rebind() method is used to add or replace a binding. It accepts the same arguments as bind() but the semantics of rebind() are such that if the name is already bound, it will be unbound and the newly given object bound:
// Create object to be bound
Fruit fruit = new Fruit("lemon");

// Perform bind
ctx.rebind("favorite", fruit);
When you run this example, it will replace the binding created by the bind() example.

Removing a Binding

To remove a binding, you use the unbind()(in the API reference documentation) method:
// Remove binding
ctx.unbind("favorite");
When you run this example, it removes the binding that was created by the bind() or rebind() example.


Previous | Next | Trail Map | The Basics | Naming Operations