IO流必知必会(18)——单例模式类序列化与readResolve()
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;
}
}java全栈日日学 文章被收录于专栏
java全栈每日必学,不要高估自己一年能做的事,不要低估自己十年能做的事
神州信息成长空间 151人发布