ClassCastException on RemotePortableObject.narrow

Been working on EJB with JBoss and Eclipse. I must say the XDoclet (with Ant) was a greate help in generating beans and doing packaging. Despite great tools, I met with a major error that had me stumped for 4 hours.

InitialContext ic = new InitialContext();
Object obj = ic.lookup("...");
SomeHome home = (SomeHome)PortablRemoteObject.narrow(obj, SomeHome.class);

A simple lookup like this, with a ClassCastException on the 3rd line. A class cast means the lookup was successful, someHomeObj is not null, but is not of type SomeHome (which happens to be an interface).

It usually means you’re casting to the wrong type, probably a typo or type confusion. But for my case I checked and rechecked and it was no error. No matter what I did couldn’t make the exception go away. This includes reflecting on the class, superclass and the interfaces of the object, to convince myself the types were correct.

// prints $Proxy157

// prints java.lang.reflect.Proxy

// prints SomeHome, Handle
for (Class c : obj.getClass().getInterfaces())

!!! The class actually implements SomeHome!!! But fails the narrow!!! *fumes* I even tested each line inside the narrow() implementation, and despite having implemented SomeHome, it cannot be cast into or assigned as SomeHome. (instanceof SomeHome == false, isAssignableFrom(SomeHome.class) == false, instanceof org.omg.CORBA.Object == false)

After hours of twiddling I finally found out it was because there were TWO of this interfaces being deployed, one in my ejb .jar, the other in my .war classes. The lookup returned the interface from the ejbjar, and was trying to cast it into the war interface. Therefore even though they had the same interface name (from the same package), they were 2 different classes.

To fix this i adjusted my package build, to EXCLUDE the interface classes from my war. A simple rebuild and the narrow works.


  1. Jarppe said,

    September 30, 2007 at 5:25 pm

    Thanks, I got the same problem. Thanks to you I didn’t have to spent 4 hours solving this.

  2. Ria said,

    October 8, 2008 at 2:53 pm

    You are my savior!!! I’ve been working for this my whole day ! >.<