Java : Serializable (直列化) - API使用例
Serializable (Java SE 19 & JDK 19) の使用例まとめです。
 だいたいのメソッドを網羅済みです。
 API仕様のおともにどうぞ。
概要
クラスの直列化可能性は、java.io.Serializableインタフェースを実装するクラスによって有効になります。
Serializable インタフェースを実装したクラスは、オブジェクトの
- シリアライズ(直列化)
 - デシリアライズ(復元)
 
が可能になります。
 例えば、オブジェクトを直列化してファイルに保存し、そのデータからオブジェクトを復元できます。
直列化の仕様については、下記のドキュメントもご確認ください。
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
}
 
      注意!
デシリアライズには潜在的な脆弱性があります。
 安易に Serializable を使わずに、代わりの手段が取れるのならばそちらも検討してみましょう。
もし、Serializable を使わなければならないときは、下記の公式ドキュメントをよくご確認ください。



