![]() ![]() ![]() ![]() |
Object Factories |
The attributes exampleillustrates how an instance of a DirContext class Drink is stored and subsequently looked up from the directory. When the Drink object's attributes are looked up from the directory, the Context.lookup()
method turned these attributes into an instance of Drink.
This was made possible because:Drink d2 = (Drink) ctx.lookup("cn=favDrink");DrinkFactory.getObjectInstance() first verifies that the object is intended for its factory. It does this by checking that the object is a DirContext and that it contains an "objectclass" attribute with a value of "drink". If this verification fails, it returns null. Otherwise, it gets the value of the "drinkType" attribute (in this case "water") and uses it to create an instance of Drink. The NamingManager, having gotten a non-null answer from an object factory, will return this value to lookup(). The definition of DrinkFactory.getObjectInstance() is as follows:
- The service provider being used (the LDAP provider) invoked NamingManager.getObjectInstance()
on the data (a DirContext) the provider read from the directory for the entry "cn=favDrink".
- The client program identified the object factory (DrinkFactory) to use when it created the initial context:
// So that object factory can be found env.put(Context.OBJECT_FACTORIES, "DrinkFactory");public Object getObjectInstance(Object obj, Name name, Context ctx, Hashtable env) throws Exception { if (obj instanceof DirContext) { DirContext thisCtx = (DirContext)obj; try { Attributes attrs = thisCtx.getAttributes(""); Attribute oc = attrs.get("objectclass"); if (oc != null && oc.contains("drink")) { Attribute dt = attrs.get("drinkType"); String drinkType = (String)dt.get(); return new Drink(drinkType); } } catch (NamingException e) { // debug System.err.println(e); e.printStackTrace(); } } // return null to indicate other factories should be tried return null; }Object Factories: End of Lesson
![]()
![]()
What's next? Now you can:
- Continue on in this trail lesson to read about the physical representation of Java objects in the directory.
- Go to the Beyond the Basics
trail to learn about advanced JNDI topics.
![]() ![]() ![]() ![]() |
Object Factories |