Java Record Serializable Example

1. Introduction

This blog post discusses the use of Java Records in the context of serialization. Records, introduced in Java 16, provide a concise way to declare data carrier classes. We will explore how these records can be made serializable, enabling them to be used in contexts like object serialization and deserialization.

Definition

Serialization is the process of converting an object into a byte stream, enabling the object to be easily saved to disk or transmitted over a network. Java Records, being immutable data carriers, are inherently suitable for serialization. However, to actually serialize a record, it must implement the Serializable interface.

2. Program Steps

1. Define a record that implements the Serializable interface.

2. Serialize the record to a file.

3. Deserialize the record from the file.

3. Code Program

import java.io.*;

// Serializable record
public record User(String name, int age) implements Serializable {}

public class SerializationExample {
    public static void main(String[] args) {
        User user = new User("Alice", 30);

        // Serialize the User object to a file
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Deserialize the User object from the file
        User deserializedUser = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
            deserializedUser = (User) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (deserializedUser != null) {
            System.out.println("Deserialized User: " + deserializedUser);
        }
    }
}

Output:

Deserialized User: User[name=Alice, age=30]

Explanation:

1. The User record, which implements the Serializable interface, can be serialized and deserialized.

2. An instance of User is created and then serialized to a file named user.ser using an ObjectOutputStream.

3. The User object is deserialized from the file user.ser using an ObjectInputStream.

4. The output confirms that the User object has been successfully deserialized, demonstrating the compatibility of Java Records with serialization.

5. This example illustrates the utility of records in Java for scenarios requiring serialization of immutable data structures.


Comments