bookmark

Java custom serialization using readObject and writeObject


Description

public class User implements Serializable {

//class attributes, constructors, setters and getters as shown above

/**
 * Always treat de-serialization as a full-blown constructor, by validating the final state of the de-serialized object.
 */
private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException 
{
    // perform the default de-serialization first
    aInputStream.defaultReadObject();

    // make defensive copy of the mutable Date field
    dateOpened = new Date(dateOpened.getTime());

    // ensure that object state has not been corrupted or tampered with malicious code
    //validateUserInfo();
}

/**
 * This is the default implementation of writeObject. Customize as necessary.
 */
private void writeObject(ObjectOutputStream aOutputStream) throws IOException {

    //ensure that object is in desired state. Possibly run any business rules if applicable.
    //checkUserInfo();

    // perform the default serialization for all non-transient, non-static fields
    aOutputStream.defaultWriteObject();
}

}

Preview

Tags

Users

  • @jil

Comments and Reviews