← 中文资源

简体中文版本

序列化代理模式

用 serialization proxy 做序列化:线上只写代理类,readResolve 回到构造器重跑校验,反序列化路径绕不过不变量。

阅读英文原文

实现说明

活动部件是类 Invoice、private、Proxy和函数 Invoice、readResolve、writeReplace。 资源声明在 try-with-resources 头部,任何退出路径都会自动关闭,无需 finally 块。失败是响亮的:IllegalArgumentException、InvalidObjectException 在守卫分支上直接中止当前操作,不做降级。

使用要点

  • 跑完文件,输出里会留下标记——restored:。
  • 执行文件,main 会按顺序走完 Invoice。

常见问题

前置条件不满足时如何报错?

代码会抛出 IllegalArgumentException、InvalidObjectException。请在调用点处理,或有意让它向上传播。

运行「序列化代理模式」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 restored: 标签标明各步骤。

入口签名:public Invoice(String customer, int cents)

核心语句

return new Invoice(customer, cents); // goes back through the constructor, so deserialization cannot bypass the invariants
}
throw new IllegalArgumentException("negative cents");
throw new InvalidObjectException("proxy required");

代码示例

import java.io.*;

public class Invoice implements Serializable {

    private static final long serialVersionUID = 1L;
    private final String customer;
    private final int cents;

    public Invoice(String customer, int cents) {
        if (cents < 0) {
            throw new IllegalArgumentException("negative cents");
        }
        this.customer = customer;
        this.cents = cents;
    }

    // serialization proxy pattern: the wire format never carries the real class
    private static class Proxy implements Serializable {
        private static final long serialVersionUID = 1L;
        private final String customer;
        private final int cents;

        Proxy(Invoice invoice) {
            this.customer = invoice.customer;
            this.cents = invoice.cents;
        }

        private Object readResolve() {
            return new Invoice(customer, cents); // goes back through the constructor, so deserialization cannot bypass the invariants
        }
    }

    private Object writeReplace() {
        return new Proxy(this);
    }

    private void readObject(ObjectInputStream in) throws InvalidObjectException {
        throw new InvalidObjectException("proxy required");
    }

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {
            out.writeObject(new Invoice("acme", 4950));
        }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {
            Invoice restored = (Invoice) in.readObject();
            System.out.println("restored: " + restored.customer + " " + restored.cents);
        }
    }
}