You may want to serialize a reference to an EJB so that you can avoid looking it up again. One way to improve the performance of the client layer of an EJB application is to avoid repeated JNDI lookup calls to find an EJB. One of the best ways to do this is to save the EJB reference in a persistent format once the client looks it up.

In our example we use an instance of the Handle class as the saved reference. Since EJB handles are serializable, we can persist them using an object output stream for later retrieval and use.

public class BeanSaver {

  public final void example() {
    // first retreive home interface:
    SomeBeanHome home = getSomeBeanHome();
    SomeBean bean = null;
    try {
      // create EJB instance:
      bean = (SomeBeanPortableRemoteObject.narrow(
        home.create(), SomeBean.class);

      // and save it to a file:
    catch (Exception e) {

  private final void saveBean(SomeBean beanthrows Exception {
    // create object output stream:
    ObjectOutputStream output = new ObjectOutputStream(
      new FileOutputStream("Bean.obj"));

    // store the reference:
  private final SomeBeanHome getSomeBeanHome() {
    // retreive home interface: