![]() ![]() ![]() ![]() |
Naming Operations |
The Context interface contains methods for adding, overwriting, and removing a binding in a context.Adding a Binding
The Context.bind()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:
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.// Create object to be bound Fruit fruit = new Fruit("orange"); // Perform bind ctx.bind("favorite", fruit);If you run this example twice, the second attempt will fail with a NameAlreadyBoundException
because the name "favorite" is already bound. For the second attempt to succeed, you will have to use rebind()
.
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:When you run this example, it will replace the binding created by the bind() example.// Create object to be bound Fruit fruit = new Fruit("lemon"); // Perform bind ctx.rebind("favorite", fruit);Removing a Binding
To remove a binding, you use the unbind()method:
When you run this example, it removes the binding that was created by the bind() or rebind() example.// Remove binding ctx.unbind("favorite");
![]() ![]() ![]() ![]() |
Naming Operations |