1. 程式人生 > >單例模式序列化與反序列化

單例模式序列化與反序列化

int nts 如果 mex res tac tor cep ios

package com.wz.thread.resolve;

import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* 序列化與反序列化
* @author Administrator
*
*/
public class MyObject implements Serializable {
private static final long serialVersionUID = 6073053711056996533L;

// 內部類的方式
private static class MyObjectHandler{
private static final MyObject myObject = new MyObject();
}

private MyObject() {}
public static MyObject getInstance() {
return MyObjectHandler.myObject;
}
// 如果沒有反序列化,讀到的和存的就是兩個對象
protected Object readResolve() throws ObjectStreamException{
System.out.println("調用了readResolve方法");
return MyObjectHandler.myObject;
}

}

package com.wz.thread.resolve;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SaveAndRead {

public static void main(String[] args) {
try {
MyObject myObject = MyObject.getInstance();
FileOutputStream fosRef = new FileOutputStream(new File("myObjectFile.txt"));
ObjectOutputStream oosRef = new ObjectOutputStream(fosRef);
oosRef.writeObject(myObject);
oosRef.close();
fosRef.close();
System.out.println(myObject.hashCode());
} catch (Exception e) {
e.printStackTrace();
}

try {
FileInputStream fisRef = new FileInputStream(new File("myObjectFile.txt"));
ObjectInputStream iosRef = new ObjectInputStream(fisRef);
MyObject myObject = (MyObject)iosRef.readObject();
iosRef.close();
fisRef.close();
System.out.println(myObject.hashCode());
} catch (Exception e) {
e.printStackTrace();
}
}

}

單例模式序列化與反序列化