HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
Getting All Your Beans from One Bag, by Nathan Cuka

Imagine this scenario: you've written all the appropriate interfaces and implementations for an EJB and now it's time to use it in client code. First you get a bean reference. Everything is simple enough: use JNDI to get the home interface, call a create method on it and catch all the possible exceptions. Voilá, a usable EJB reference. No big deal. However, after creating the bean and looking at the number of beans you want to use, you realize you'll be doing the same thing over and over again. You shake your head and say, "There has to be a better way to create these objects."

Fortunately, there is. Polymorphism and the reflection API provide a powerful and flexible mechanism for obtaining EJB references.

Without using reflection or polymorphism, you'd obtain references something like this:

try {
// Use a helper method to get the JNDI context to use for lookups...
InitialContext context = getJNDIContext();

// Then lookup the bean home interface and create the bean
String jndiName = "com/zefer/util/MyBeanHome";
MyBeanHome myHome = (MyBeanHome) context.lookup(jdniName);
IMyBean myBean = (myBean) myHome.create();

} catch (...){
// Catch all the exceptions...

Granted, this isn't the most complicated code in the world, but it can lead to problems with code management. What happens when you want references for several different beans? If you use casting, as in the example above, your code would be different for each bean since you have to hard-code the objects you're casting to. And what does the code look like if you want to use several different create methods? Again, you'd need separate code segments for each situation. The upshot is, you'd have similar-looking code. No matter how simple the code is, large amounts of duplicate code can be extremely difficult to manage.

This particular situation rings a bell for OO analysts – it's similar to a specialization relationship or creational operation that's most likely covered by a design pattern. Indeed, several design patterns directly address this situation: Strategy, Builder and Factory, to name a few. Some patterns, such as the Builder pattern, appear to be overkill as the differences in code are so slight and the number of situations so varied that the application of this pattern implies a large number of trivial classes. This large number effectively changes the nature of the problem to one of object management rather than code management, so it doesn't really improve the situation. Other techniques, such as delegation, provide an easier way to manage the code. Using delegation, every single procedure that gets a reference would be hard-coded in; therefore it's not very flexible in its application.

Even a strict application of the Factory pattern may leave a lot to be desired in terms of reducing the complexity of the code and the design. Thus the straightforward application of classic designs needs to be rethought in order to streamline the design and code for obtaining EJB references.

Luckily, the power of polymorphism and the Java reflection API come to the rescue. The latter provides the ability to invoke arbitrary method calls on arbitrary objects (as long as that method exists for that object, of course!). In our situation we want to invoke arbitrary create methods for enterprise beans. The concept of polymorphism comes into play in the client code after we've created EJB objects and want to cast them to an appropriate bean type. With these two items in hand it's possible to write a single class with a few methods that can handle every single creation scenario for any bean.

For this article I've constructed a class named EJBFactory using Netscape Application Server 4.0 and its EJB 1.0 implementation. The responsibility of the EJBFactory class is to return EJBObject references (see Listing 1). This class contains three fairly straightforward methods:

  1. setJNDIFinder(): Sets a reference to an object that provides a wrapper around JNDI contexts and lookup services
  2. getHomeInterface(): Gets a reference to a particular home interface for a bean
  3. createBean(): Creates an EJBObject reference
The first two methods are simple, containing little (if anything) that's surprising. The third method, createBean(), does the bulk of the work despite its deceptively diminutive size.

The createBean() method creates beans using the same process outlined above, namely, the method first obtains the home interface from JNDI, then calls the appropriate create() method on the home interface. For this method the first parameter to the method specifies the particular home interface to retrieve from JNDI. The appropriate create method is defined as the one that matches the signature of the objects in the Vector parameter to the method. To get the proper create method for the EJB home interface, the createBean() method first reflects the Vector parameter to get the classes of the object it contains, then reflects the home interface returned from JNDI to get a reference to the proper create method. After getting this reference, invoking the method to create the bean is a trivial task.

Using reflection in this manner allows the createBean() method to create any type of bean using any type of create method. After creating the bean, the method still has to return it. To work with disparate types of beans, the createBean() method relies on the fact that all the remote stubs for EJBs inherit from the EJBObject class. This allows the client code to use the object normally after either downcasting the returned object (for EJB 1.0) or calling the javax.rmi.PortableRemoteObject.narrow(...) method (per section 5.9 of the EJB 1.1 specification) on the object. Thus, by exploiting polymorphism, the client code can access the returned bean just as if it had been created using a more verbose method.

There are three main objections with this approach:

  1. Reflection may be an expensive operation, so we have the classic flexibility versus performance trade-off. This trade-off is something that may be answered only on a situational basis.
  2. The createBean() method throws a number of exceptions, thereby begging the question of whether this method of creating beans reduces duplicate code. However, the creation of a small wrapper class to handle these exceptions and throw application-defined exceptions solves this problem (see Listing 2).
  3. Creating beans in this manner doesn't handle inheritance in the bean-create calls. In other words, if you try to use a create method that has a parent class as its signature, with a child class as the actual parameter, the bean won't be created appropriately. Unfortunately, I haven't found an elegant way around this final objection as it appears to be a limitation in the reflection API.
In spite of these objections, the EJBFactory class brings a number of benefits. It greatly reduces code duplication, making code more compact and easier to maintain, extend and debug. Creating beans is extraordinarily easy since the code consists of a single method call and an associated catch block (see Listing 3). Furthermore, the flexibility of the EJBFactory allows you to easily extend an EJB-based system to include new beans without having to modify any code. Now that's a scenario worth imagining!

Author Bio
Nathan Cuka is a senior software engineer for Zefer Corp. He can be contacted at: [email protected]


Listing 1


import java.util.*; 
import java.lang.reflect.*; 
import javax.ejb.*; 
import javax.naming.*; 

* A general purpose EJB factory.  If you wanted to  
* use the abstract factory design pattern here, you could 
* have this class implement a generic interface to provide 
* a higher degree of abstraction.  That level of abstraction 
* was not really needed for this example.  

public class EJBFactory { 
   private JNDIFinder _jndiFinder = null; 
   /** This constructor sets the JNDIFinder to use.  The JNDIFinder class is  
   * a wrapper around JNDI functionality such as object lookups.  
   public EJBFactory(JNDIFinder finder) { 
   /** Method to get the home interface for an EJB with 
   * the specified JNDI name.  The method it uses for lookup 
   * is through a helper JNDIFinder object.
   * @param jndiName  The name of the EJB object to get 
   * @return An Object that is the home interface 
   * @throws javax.naming.NameNotFoundException if the 
   *         name does not exists in JNDI.  Also throws 
   *         javax.naming.NamingException if there is  
   *         a problem in looking up the name. 
   public Object getHomeInterface(String jndiName) throws 
      Object obj = null; 
      obj = _jndiFinder.lookup(jndiName); 
      return obj; 

   /** Method to create an enterprise bean.  Right now the 
   * Vector of params is getting reflected to determine their  
   * class type. 
   * This might be an expensive operation and so we might  
   * want to use something more efficient in the future to 
   * speed things up.  The important thing to remember is 
   * that ORDER IS IMPORTANT for these parameters.  Otherwise 
   * if you have a create method that takes multiple parame-
   * ters of the same type, then you will get the method 
   * invocation wrong. 
   * @param jndiName  The JNDI name of the EJB 
   * @param params    A vector containing the arguments to 
   * the create method. 
   * @return An EJBObject that references the remote inter
   * face for the specified EJB runtime instance.  It is safe 
   * to down cast this reference to a specific remote inter
   * face type. 
   * @throws InvocationTargetException or IllegalAccessExcep-
   * tion if the method has trouble invoking the create 
   * method.  See the java.lang.reflect.Method class for 
   * details on these exceptions.  Also throws javax.naming.*   
   * exceptions if there is a lookup failure of the home 
   * interface of the specified EJB.   A RemoteException is 
   * thrown per standard EJB rules.  Throw a generic excep-
   * tion so that any subclasses (e.g. wrappers) can  throw 
   * their own exceptions. 
   public EJBObject createBean( String jndiName, Object      
      throws InvocationTargetException, 
      Exception { 
      EJBObject bean = null; 
      // Get the home interface and its associated Class 
      // object.  We need the Class object for reflection... 
      Object homeInterface = getHomeInterface(jndiName); 
      Class beanClass = homeInterface.getClass(); 
      // Need a class array for the method lookup... 
      Class[] signature = getSignature(params); 
      // Look up the method--throw exception if method not 
      // there. 
      // All create methods in the home interface are named 
      // "create" so search for the create method with the 
      // appropriate  signature 
      Method createMethod = beanClass.getDeclaredMethod("cre-
       ate",  signature); 
      // This is the key.  Here homeInterface is a reference 
      // to a REAL remote object -- i.e. the skeleton class 
      // on the server.  The invocation is done on this spe-
      // cific instance of the remote object created by the 
      // EJB container on the server. 
      bean = (EJBObject) createMethod.invoke(homeInterface,  
      return bean; 
   /** Method to construct an array of Class objects repre-
   * senting a method signature 
   * @param parameters  A vector whose elements will be 
   * reflected or their specified Classes. 
   * @return A Class array  
   private Class[] getSignature(Object [] parameters) { 
      Class sig[] = new Class[parameters.length]; 
      for(int i =0; i<sig.length; i++) { 
         sig[i] = parameters[i].getClass(); 
      return sig; 
   /** Method to set the internal JDNIFinder variable */ 
   private void setJNDIFinder(JNDIFinder finder) { 
      jndiFinder = finder; 

Listing 2

package com.myapp.util; 

import java.util.*; 
import javax.naming.*; 

* Class to wrap the EJBFactory to handle the number of exceptions 
* that the factory throws.  By wrapping the factory, it is easier to use 
* its functionality in application code.  
public class FactoryWrapper extends EJBFactory { 

/* Method to create an enterprise bean. */ 
public EJBObject createBean( String jndiName, Object []params) 
   throws  AppException 
      EJBObject bean = null; 
      try { 
         bean = super.createBean(jndiName, params); 
      } catch (InvocationTargetException e) { 
         throw new AppException(e.getMessage()); 
      } catch (NoSuchMethodException e) { 
         throw new AppException(e.getMessage()); 
      } catch (IllegalAccessException e) { 
         throw new AppException(e.getMessage()); 
      } catch (javax.naming.NameNotFoundException e) { 
         throw new AppException(e.getMessage()); 
      } catch (javax.naming.NamingException e) { 
         throw new AppException(e.getMessage()); 
      } catch (java.rmi.RemoteException e) { 
         throw new AppException(e.getMessage()); 
      } catch (Exception e) { 
         throw new AppException(e.getMessage()); 
      return bean; 

Listing 3

/* Code example to create a bean using a create method 
 * that has a signature of create(String).  This example 
 * uses the FactoryWrapper class from Code Example 2.  
 * The JNDIFinder class mentioned is a simple wrapper 
 * around a JNDI context.  The code is not given here 
 * for the sake of brevity. 
 try { 
    FactoryWrapper factory = new FactoryWrapper(); 
    // The finder variable is created outside of this scope 
    String username = "Foo"; 
    String jndiName = "com/foo/entity/myAppBean"; 
    Object [] createArgs = { username }; 
    myAppBean bean = (myAppBean) factory.createBean(jndiName, 
    } catch (ApplicationException e) { 
    // ... Error handling code ... 


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.