有一个User类,用来配合序列化和反序列化:
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -1742192753123642925L;
public String name;
public User() {
this.name = "张三";
}
}
一个简单的序列化工具类,如下:
package com.example.goodforjava.util;
import java.io.*;
/**
* 序列化和反序列化的方法
*/
public class SerializationUtils {
private static final String FILE_NAME = "/Volumes/小可爱/文档/test.bin";
/**
* 序列化
*/
public static void writeObject(Serializable s) throws IOException {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME));
oos.writeObject(s);
} catch (Exception e) {
e.printStackTrace();
} finally {
oos.close();
}
}
/**
* 反序列化
*
* @return
* @throws IOException
*/
public static Object readObject() throws IOException {
Object obj = null;
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(FILE_NAME));
obj = objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
objectInputStream.close();
}
return obj;
}
}
把一个User实例序列化进磁盘,如下:
public static void main(String[] args) throws IOException {
//写到磁盘中
SerializationUtils.writeObject(new User());
}
再修改下User类的构造函数,如下:
把数据从磁盘反序列化为对象,如下:
public static void main(String[] args) throws IOException {
//反序列化
User user = (User) SerializationUtils.readObject();
System.out.println(user.name);
}
输出结果为:
可以发现即使User在构造函数中把name属性初始化的值改成了王五,反序列回来的name属性的值却还是张三。
总结
从以上测试结果证明,反序列化时,类的构造函数不会被执行,否则的话,name属性的值就应该是王五。