Object Serialization in Java

Object serialization is an essential mechanism in Java programming, allowing objects to be converted into a sequence of bytes, which can then be stored in files, transmitted over networks, or simply kept in memory for later use. The reverse process, known as deserialization, reconstitutes the object from this sequence of bytes.

Why Serialize Objects?

Serializing objects is useful in several situations, such as:

  • Save the state of an object for future use.
  • Send objects over a network in distributed applications.
  • Store objects in databases, converting them into byte arrays.

How to Serialize Objects in Java

In Java, an object is serializable if its class implements the java.io.Serializable interface. This interface is a markup interface, that is, it does not have methods to be implemented, but it indicates to the JVM that objects of this class are enabled for serialization.


import java.io.Serializable;

public class ObjectExample implements Serializable {
    private static final long serialVersionUID = 1L;
    private String attribute;

    // Constructors, getters and setters
}

The serialVersionUID field is a unique identifier for the serializable class, which is used during deserialization to ensure that the loaded class is compatible with the serialized version of the object.

To serialize an object, you can use ObjectOutputStream, which is a wrapper for an output stream that supports object serialization.


import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class Serializer {
    public static void serialize(StringFilePath, ExampleObjectObject) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(Filepath))) {
            oos.writeObject(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Object Deserialization

To deserialize, you use ObjectInputStream, which can read the sequence of bytes from an input stream and reconstruct the object.


import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class Deserializer {
    public static ExampleObject deserialize(StringFilePath) {
        ExampleObject object = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filepath))) {
            object = (ExampleObject) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
}

Important Considerations

When working with serialization, there are several considerations to take into account:

  • Security: Serialization can be an attack vector if data is not properly validated during deserialization.
  • Version Compatibility: Changes to the serialized class can make previous versions incompatible unless carefully managed.
  • Transient Fields: Fields marked with the transient keyword are not serialized. This is useful for sensitive data or to avoid unnecessary serialization.

Custom Serialization

In cases where you need finer control over the serialization process, you can implement the writeObject and readObject methods in your class:


import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;

public class CustomObjectExample implements Serializable {
    private transient String attributeNaoSerializado;

    private void writeObject(ObjectOutputStream oos) throws IOException {
        oos.defaultWriteObject();
        // Custom code to serialize attributeNaoSerializado
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        ois.defaultReadObject();
        // Custom code to deserialize attributeNaoSerializado
    }
}

These methods allow you to add additional logic during serialization and deserialization, such as encrypting sensitive data or including transient fields.

Conclusion

Object serialization is a powerful tool in Java that allows object persistence, inter-process communication, and other advanced functionality. However, it is necessary to use it with caution, considering aspects such as security and version compatibility. Mastering serialization and deserialization is essential for Java developers who work with applications that require data exchange between different componentsor systems.

Now answer the exercise about the content:

Which of the following statements about object serialization in Java is true?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Lambda Expressions in Java

Next page of the Free Ebook:

115Lambda Expressions in Java

5 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text