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();
}
}
}