How should I declare fields within my serializable class to prevent them from being serialized?

Govind Seshadri

Within JDK 1.1, any non-static field declared as transient is not serialized. (Static fields are not serialized anyway)

Java 2 provides you with another mechanism for specifying which fields need to be serialized. Your class can declare the static field:

public final ObjectStreamField[] serialPersistentFields = {...};

initialized with instances of ObjectStreamField, within each instance indicating the name and type of the serializable field.

For example:

public class FooBar implements Serialzable {
  private Foo foo;
  private int bar;
  private String passwd;

  public final static ObjectStreamField[]
    serialPersistentFields = {
      new ObjectStreamField("foo",Foo.class),
      new ObjectStreamField("bar",Integer.TYPE)
    };
}

indicates that only the fields foo and bar must be serialized.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact