How should I declare fields within my serializable class to prevent them from being serialized?
Created May 4, 2012
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.