Listing the Children of a Context

A common JNDI operation is retrieving the list of names of an object’s children. For example, an application might get the names of Enterprise JavaBeans in a Java application server, or list the names of user profile information in an LDAP server in order to populate a Swing JTree component in an address-book application. You list the names of an object’s children using the list( ) method of Context:

NamingEnumeration children = initialContext.list("");

The list( ) method returns a javax.naming.NamingEnumeration of javax.naming.NameClassPair objects, where each NameClassPair contains the name and class of a single child of the Context. Note that the NameClassPair is not the child itself. Its getName( ) method, however, enables us to learn the name of the child, while getClassName( ) lets us access the child’s class name. The NamingEnumeration implements the java.util.Enumeration interface, so it allows us to loop through the results of calling list( ) using the familiar enumeration methods. JNDI actually uses NamingEnumeration as the return type of a number of naming operations; the actual objects in the enumeration vary depending on the operation.

Example 7-6 shows the implementation of a list command for our NamingShell . Because executing list( ) requires a current Context, the execute( ) method queries the shell to determine whether one exists. If there is no current Context, the method throws an exception.

Example 7-6. The list Command ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.