Java 对象序列化中单例模式序列化怎么保护
在 java 对象序列化中,保护单例模式不被破坏的核心做法是在单例类中实现 readresolve() 方法。该方法会在反序列化完成后、返回新对象之前被调用,通过返回类的唯一实例来覆盖反序列化生成的新对象,从而确保全局只有一个实例存在。

为什么反序列化会破坏单例
反序列化机制默认会为每个读取到的字节流创建一个新的对象实例,这会导致原本的单例变成多个独立的对象,破坏了单例模式的约束。

import java.io.*;
public class Singleton implements Serializable {
private static final long serialVersionUID = 1L;
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
// 关键:防止反序列化破坏单例
protected Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public void doSomething() {
System.out.println("Singleton is working.");
}
public static void main(String[] args) throws Exception {
// 序列化
Singleton original = Singleton.getInstance();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(original);
oos.close();
// 反序列化
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Singleton deserialized = (Singleton) ois.readObject();
ois.close();
// 验证
System.out.println("Original: " + System.identityHashCode(original));
System.out.println("Deserialized: " + System.identityHashCode(deserialized));
System.out.println("Are they the same? " + (original == deserialized));
}
}
使用枚举单例的替代方案
除了实现 readResolve(),更推荐的方式是使用枚举(Enum)来实现单例。枚举类型天然支持序列化且不会受到反射或反序列化的影响,是防止单例被破坏的最安全方式。

import java.io.*;
public enum EnumSingleton {
INSTANCE;
public void doSomething() {
System.out.println("Enum Singleton is working.");
}
public static void main(String[] args) throws Exception {
// 序列化
EnumSingleton original = EnumSingleton.INSTANCE;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(original);
oos.close();
// 反序列化
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
EnumSingleton deserialized = (EnumSingleton) ois.readObject();
ois.close();
// 验证
System.out.println("Original: " + System.identityHashCode(original));
System.out.println("Deserialized: " + System.identityHashCode(deserialized));
System.out.println("Are they the same? " + (original == deserialized));
}
}
基于 readResolve 的具体问题
如果单例类中有非静态字段,readResolve() 是否能正确恢复这些字段的值?答案是肯定的,因为 readResolve() 是在对象完全反序列化之后调用的,此时对象的字段已经被填充,但返回的是预先定义的 INSTANCE,所以非静态字段会被忽略,始终返回唯一的实例。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











