java中有一个与writeReplace()相对的方法readReasolve(),该方***在readObject之后调用,可以实现保护性的复制整个对象。所有的单例类在实现序列化时,都应该重写readReasolve()方法,这样才能确保在反序列化回来后的对象与单例对象是同一对象(反序列化恢复对象不需要调用构造器)。参考下列代码。
public class School implements Serializable { public static School highSchool = new School(); private School() { } } public class readResolveTest { public static void main(String[] args) throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( "test.txt")); ObjectInputStream ois = new ObjectInputStream(new FileInputStream( "test.txt")); oos.writeObject(School.highSchool); School sch = (School) ois.readObject(); //false System.out.println(sch == School.highSchool); } }
将school中的readResolve重写后,readResolveTest将输出true。
public class School implements Serializable { public static School highSchool = new School(); private School() { } public Object readResolve() { return highSchool; } }