serialization

Serialization

Serialization is the process of converting objects into a byte stream ...to enable data storage, sharing, and retrieval in a compact, standardized format..

How to serialize an object?

// Class you want to serialize should `implements Serializable`
public class User implements Serializable {
    private String name;
    private String password;

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Result :

Object serialized into byte code to file UserInformation.ser

Alt text

Deserialize

Deserialize is the process of converting a byte stream into objects (essentially reverse of serialize)

Since we stored a User object with name 'aloy' and password 'aaaaa' and serialized it into UserInformation.ser , now we want to deserialize it .

Result :

Deserialize

Take Note: Can used transient to mark variables in object to be not serialized

Serial Version UID

When deserializing an object, the JVM compares the serialVersionUID of the class being loaded with the serialVersionUID that was stored with the object.

If they match, deserialization proceeds; if they don't match, a InvalidClassException is thrown, indicating a class version mismatch.

To avoid this...

Make sure that both class structure of the serialized objects should be the same on both sides

or

Set a unique serial version UID for both object classes for serialization and deserialization

Last updated