Java : Serializable with Examples

Serializable (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Serializable methods.


Summary

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

Class diagram

Please see also : Java Object Serialization Specification (Java SE 19)

public class Sample implements Serializable {
    @Serial
    private static final long serialVersionUID = -7890552026025073127L;

    private final String text;
    private final int num;

    public Sample(String text, int num) {
        this.text = text;
        this.num = num;
    }

    @Override
    public String toString() {
        return "[text=%s, num=%d]".formatted(text, num);
    }
}
final var file = Path.of("sample.data");
System.out.println(file); // sample.data

final var src = new Sample("abc", 123);
System.out.println(src); // [text=abc, num=123]

try (final var os = new ObjectOutputStream(Files.newOutputStream(file))) {
    os.writeObject(src);
}

final var bytes = Files.readAllBytes(file);

// [-84, -19, 0, 5, 115, 114, 0, 6, 83, 97, 109, 112, 108, 101, -110, 127, 32,
//  -68, -1, 9, 102, 25, 2, 0, 2, 73, 0, 3, 110, 117, 109, 76, 0, 4, 116, 101,
//  120, 116, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83,
//  116, 114, 105, 110, 103, 59, 120, 112, 0, 0, 0, 123, 116, 0, 3, 97, 98, 99]
System.out.println(Arrays.toString(bytes));

try (final var is = new ObjectInputStream(Files.newInputStream(file))) {
    final var dst = is.readObject();
    System.out.println(dst); // [text=abc, num=123]
    System.out.println(dst.getClass().getSimpleName()); // Sample
}

Warning!

Deserialization of untrusted data is inherently dangerous. You should check the following official documentation.


Related posts

To top of page