简体   繁体   中英

Create your own Serializable interface to persist the state of the object

Often it has been asked in interviews how you can create an interface as serializable. The question arises that if we try to check serializable API it does not include any method as it is marker interface, If we try to override the same functionality in user defined interface. If the class instead of implementing serialzable interface creates own serializable interface,will it be achieved? How the same serializable functionality will be implemented? How will it serialize object or persists the state of the object?

Create your custom serialization with implementing readObject() and writeObject() methods. This behavior will override the default serialization behavior.

  • Inside writeObject() method, write class attributes using writeXXX methods provided by ObjectOutputStream.
  • Inside readObject() method, read class attributes using readXXX methods provided by ObjectInputStream.
  • Please note that the sequence of class attributes in read and write methods MUST BE same.

Example: public class User implements Serializable {

private static final long serialVersionUID = 7829136421241571165L;

private String firstName;
private String lastName;
private int accountNumber;
private Date dateOpened;

public User(String firstName, String lastName, int accountNumber, Date dateOpened) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.accountNumber = accountNumber;
    this.dateOpened = dateOpened;
}

public User() {
    super();
}

//Setters and Getters

private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException
{      
    firstName = aInputStream.readUTF();
    lastName = aInputStream.readUTF();
    accountNumber = aInputStream.readInt();
    dateOpened = new Date(aInputStream.readLong());
}

private void writeObject(ObjectOutputStream aOutputStream) throws IOException
{
    aOutputStream.writeUTF(firstName);
    aOutputStream.writeUTF(lastName);
    aOutputStream.writeInt(accountNumber);
    aOutputStream.writeLong(dateOpened.getTime());
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM