java

序列化一个对象只需要让他实现Serializable接口(这是一个“标记接口”,tagging interface,没有任何方法)就行,但是,当语言引入序列化概念之后,它有很多标准类库的类,包括primitive的wrapper类,所有的容器类,以及别的很多类,都会相应的发生改变,甚至连Class对象都会被序列化。
要想序列化对象,必须先创建一个OutputStream,然后把它嵌进ObjectOutputStream。这是就能调用writeObject() 方法把对象写入OutputStream, 读的时候需要把InputStream嵌到ObjectInputStream中,然后在调用readObject()方法。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class SerSingleton implements java.io.Serializable{
String name;
private SerSingleton(){
System.out.println("Singleton is create");
name = "SerSingleton";
}
private static SerSingleton instance = new SerSingleton();
public static SerSingleton getInstance(){
return instance;
}
public static void createString(){
System.out.println("CreateString in Singleton");
}
private Object readResolve(){//阻止新生成的实例,总是返回当前对象
return instance;
}
}
public void test() throw Exception{
SerSingleton s1 = null ;
SerSingleton s = SerSingleton.getInstance();
//先将实例串化到文件
FileOutputStream fos = new FileOutputStream("SerSingleton.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
oos.flush();
oos.close();
//从文件读出原来的单例类
FileInputStream fis = new FileInputStream("SerSingleton.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
s1 = (SerSingleton) ois.readObject();
Assert.assertEquals(s,s1);
}