This tip is an extension of a Design Pattern called “Service Locator” for the J2EE architecture. Generally, the “Service Locator” pattern returns a home object by merely accepting a string, usually a mapping for a JNDI name.
This tip creates a pure factory for stateless session beans (a method which accepts a string?in JNDI, the name of the stateless session bean) and returns the appropriate remote objects (called EJBObject) without actually type-casting the appropriate home object (called EJBHome) or executing the create method. The following code demonstrates:
Accounts valAccounts= ((AccountsHome)home).create();
This easiest way to call a subclass method without actually type-casting it is by using reflection:
Method m = homeBase.getMethod("create", null);remoteObject = (EJBObject) m.invoke(home, null);
Here’s the sample code:
/* Sample code */public class ResourceLocator{ public static EJBObect getResourceInstance(String jndiName) { Context ctx = new InitialContext(); Object o = ctx.lookup(jndiName); //Need not type cast home object to appropriate Home Interface home = (EJBHome) PortableRemoteObject.narrow(o, Class.forName("javax.ejb.EJBHome")); //Need not type cast home object to appropriate Remote Interface Class homeBase = home.getClass(); Method m = homeBase.getMethod("create", null); remoteObject = (EJBObject) m.invoke(home, null); return remoteObject; }}
Whichever JNDI name is provided, the above code generalizes and achieves a perfect factory pattern for a stateless session bean.