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;
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. 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 9-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 9-6. The list command
import java.util.Vector; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access