I believe almost every J2EE developer is familiar with code below:
Context initCtx = new InitialContext();
Object result = initCtx.lookup("java:comp/env/ejb/cart");
CartHome cartHome = (CartHome) javax.rmi.PortableRemoteObject.narrow(result, CartHome.class);Looks pretty much a boilerplate code? Why simple cast operator can’t serve the purpose? What
narrow() does?
Yes it is definitely boilerplate code and that’s the reason why we’re encapsulating it with Delegate design pattern and why we’ll be having
Common Annotation in the upcoming release of Java EE to simplify the EJB resource lookup.
Type narrowing allows our client program to be interoperable with all compliant EJB container implementations.
Those programs using the simple object casting for subtyping the remote and remote home interfaces are likely to fail if the container implementation uses RMI-IIOP as the underlying communication transport.
Here are the cases that
narrow() is not needed:
- If your EJB is local
- If
EJBContext lookup method is used to look up the remote home interface - When dependency injection is used instead of JNDI lookup
- If you’re happy sticking with the container implementation which is not using RMI-IIOP
PS: The RMI-IIOP subsystem is composed of APIs that allow for the use of
RMI-style programming that is independent of the underlying protocol, as well as an implementation of those APIs that supports both the J2SE native RMI protocol (JRMP) and the CORBA IIOP protocol. More details in the latest version of Java EE spec.