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.

Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.