通常情況下
一個可以被串行化的單例
public class SerSingleton implements java
String name;
private SerSingleton() {
System
//創建單例的過程可能會比較慢
name=
}
private static SerSingleton instance = new SerSingleton()
public static SerSingleton getInstance() {
return instance;
}
public static void createString(){
System
}
private Object readResolve(){ //阻止生成新的實例
return instance;
}
}
測試代碼如下
@Test
public void test() throws Exception {
SerSingleton s
SerSingleton s = SerSingleton
//先將實例串行化到文件
FileOutputStream fos = new FileOutputStream(
ObjectOutputStream oos = new ObjectOutputStream(fos)
oos
oos
oos
//從文件讀出原有的單例類
FileInputStream fis = new FileInputStream(
ObjectInputStream ois = new ObjectInputStream(fis)
s
Assert
}
使用一段測試代碼測試單例的串行化和反串行化
junit
serialization
but was:javatuning
說明測試代碼中s和s
注意
返回目錄
編輯推薦
Java程序設計培訓視頻教程
J
J
Visual C++音頻/視頻技術開發與實戰
Oracle索引技術
ORACLE
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27835.html