测试 单例通过反序列化出来就不再是单例,反序列化时会反射创建一个新的对象出来

public class SerializableSingle {
	public static void main(String[] args) throws Exception {
		ObjectOutputStream obc = new ObjectOutputStream(new FileOutputStream(new File("d:/single.txt")));
		obc.writeObject(Single003.getInstance());
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:/single.txt")));
		Single003 readObject = (Single003)ois.readObject();
		System.out.println(readObject == Single003.getInstance());//false
		
	}
}

  

解决就是在单例中定义readResolve()方法

 

 

 

posted on 2019-12-14 14:03  晴空半岛  阅读(322)  评论(0编辑  收藏  举报