Looking up an object means retrieving the object by name from the naming system of the JNDI Registry Service.
You have obtained an initial context.
The object is already bound in the naming system. Otherwise, you will get a javax.naming.NameNotFoundException.
Call Context.lookup() method passing the name of the targeted object as an argument.
More information: http://java.sun.com/j2se/1.5.0/docs/api/javax/naming/Context.html#lookup(java.lang.String)
The JNDI Registry Service handles the different object types (serializable, non-serializable and remote) differently.
// lookup the serializable object from the serializable example in Binding Objects try { // create InitialContext to access JNDI Registry Service naming system. // InitialContext creation depends on the type of the client Context ctx = new InitialContext();
String name = "serializable_binding";
Object serialObj = ctx.lookup(name);
System.out.println("Object [" + serialObj + "] is found for name [" + name + "]");
} catch (NamingException e) { e.printStackTrace(); } |
External clients that look up this object should have its class definition and the classes referred by it in their class path to perform successful deserialization of the object.
To look up a remote object, you must have its remote interface in the client’s class path (for external clients) or have a classloader reference to it (for components and applications running on the server process).
The returned result is a remote stub or proxy implementing the remote interface. This stub or proxy can be used later to invoke the interface methods remotely.
// Lookup the remote object from the remote example in Binding Objects try { // create InitialContext to access JNDI Registry Service naming system. // InitialContext creation depends on the type of the client Context ctx = new InitialContext();
String name = "remote_timer";
// lookup the remote object Object obj = ctx.lookup(name);
// use PortableRemoteObject.narrow to cast the result to the remote interface instead // of direct casting Timer myTimer = (Timer) PortableRemoteObject.narrow(obj, Timer.class);
System.out.println("Object [" + myTimer + "] is found for name [" + name + "]");
// invoke the remote method on the returned object System.out.println("Get current time: " + myTimer.getTime());
} catch (NamingException e) { e.printStackTrace(); } |
Use PortableRemoteObject.narrow() to cast the result to the remote interface instead of direct casting.
// Lookup the non-serializable object from the non-serializable example in Binding // Objects try { // create InitialContext to access JNDI Registry Service naming system. // InitialContext creation depends on the type of the client Context ctx = new InitialContext();
String name = "non_serializable_binding";
Object obj = ctx.lookup(name);
System.out.println("Object [" + obj + "] is found for name [" + name + "]");
} catch (NamingException e) { e.printStackTrace(); } |