adam bien's blog

When Is PortableRemoteObject#narrow needed? 📎

PortableRemoteObject#narrow was the default of casting of remote objects to the desired type:


Context context = new InitialContext();
Object raw = context.lookup(jndiName);
MyRemoteType type = (MyRemoteType)PortableRemoteObject.narrow(raw, MyRemoteType.class);

According to JavaDoc, the method narrow "narrows" the abstract remote type to the requested one:

"Checks to ensure that an object of a remote or abstract interface type can be cast to a desired type."

PortableRemoteObject#narrow was widely used within ServceLocator pattern implementations. In the early J2EE years most application servers relied on CORBA/IIOP (RMI over IIOP). In the CORBA / IIOP context casting and inheritance is challenging and requires the "narrowing".

Later,the popular appservers switched to optimized RMI, or even proprietary binary implementations where the PortableRemoteObject#narrow was no more required. However, for compatibility and portability reasons it was a good programming style to use always use PortableRemoteObject#narrow.

In modern Java EE architectures InitialContext#lookup of EJB / CDI components, as well as, IIOP-based communication are dying. "Don't distribute" becomes a best practice: applications are working as much as only possible locally and only exposing coarse grained interfaces, mostly via JAX-RS.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 343 in, chapter "Bean Locator"]

See you at Java EE Workshops at MUC Airport, particularly at the Java EE User Architectures workshop!