Thankfully, we’ve got handles

image with no caption
image with no caption
image with no caption

A handle is a Serializable object that knows how to get back to the original Remote EJB object. It’s not a stub, but it can GET the stub.

It has just one method, getEJBObject(), that returns type EJBObject.

So you have to narrow and cast the stub you get back!

A handle can rescue your shopping experience. Ask the bean (via the EJBObject interface) for a handle:

Handle myHandle = myCart.getHandle();

serialize it, email it to yourself, then deserialize on your work machine and you’re back in business.

The handle is a Serializable thing that knows how to get back to the stub. It has a single method:

public EJBObject getEJBObject()

So when you call it, you have to cast and narrow the stub that comes back! Remember, you always have to cast and narrow a stub unless the method that returns it has the actual Remote interface as its declared return type. Since the handle’s method has no frickin’ clue what your component interface is (say, ShoppingCart), you’re faced with the same scenario you had with the home stub you got from the JNDI lookup() method. Cast and narrow. Cast and narrow. Cast and narrow.

In your client code, you’ll have something like:

// your code to get the ...

Get Head First EJB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.