O'Reilly logo

Java Enterprise in a Nutshell, Third Edition by William Crawford, Jim Farley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Binding Objects

A Context stores its subordinates as a set of Binding objects. A binding is an association between an object and its name. Thus, as we’ve already seen, a Binding object contains an object, its name, and its class. We can add a new Binding to a Context with the bind() method. For example, here’s how to add a binding for a new file object to an existing Context:

java.io.File newfile = java.io.File("c:\temp\newfile");
tempContext.bind("newfile", newfile);

Now, if we call list() on this Context, you see a new child named newfile. Recall in the previous section we said that you have to drop out of JNDI to create a new file when using the Sun filesystem provider. The previous example shows what we meant. To create a file, use the java.io.File constructor, which isn’t part of JNDI. To bind the file into the naming system, use the bind() method of Context.

If you try to bind a name to an object, and the name has already been used, the method throws a NameAlreadyBoundException. If you want to bind a new object to an existing name, use the rebind() method instead. Context also has an unbind() method you can use to remove a binding.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required