文章目录
一、序列化是什么
二、对象如何进行序列化
1.方法
2.Student定义
@Data
public class Student implements Serializable {
private String name;
private Integer age;
private Integer score;
}
3.序列化方法
public class SerializeUtils {
public static final String PATH = "student.txt";
public static void serialize() throws IOException {
Student student = new Student();
student.setName("test");
student.setAge(18);
student.setScore(99);
//写好的目标文件在当前工作目录detail下。 PATH = "student.txt";
//PATH,也可以使用绝对路径
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(new File(PATH)));
outputStream.writeObject(student);
outputStream.close();
System.out.println("序列化成功!已经生成student.txt文件");
System.out.println("==============================================");
}
public static void deserialize() throws IOException, ClassNotFoundException {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File(PATH)));
Object obj = inputStream.readObject();
System.out.println("obj的运行类型是 = " + obj.getClass());
Student student = (Student) obj;
inputStream.close();
System.out.println("反序列化结果为:");
System.out.println( student );
}
}
4.序列化结果
public class MainApplication {
public static void main(String[] args) throws IOException, ClassNotFoundException {
SerializeUtils.serialize();
SerializeUtils.deserialize();
}
}
三、Serializable接口有何用?
Serializable是一个空接口,但是,序列化的对象,如果不实现这个接口。
那么,就不可以将对象序列化。
四、serialVersionUID号有何用?
1.不添加UID进行序列化
相信你一定经常看到有些类中定义了如下代码行,即定义了一个名为serialVersionUID的字段:
private static final long serialVersionUID = -4392658638228508589L;
调用之前的序列化对象方法,将对象序列化。
2.在Student类添加一个新的字段
3.反序列化对象
接下来,将第1步序列化好的对象,进行反序列化。
4.UID作用
5.自动生成UID
6.结果
添加字段、减少字段。
反序列化,可以成功
五、特殊情况
六、序列化的受控和加强
七、单例模式增强
public class Singleton implements Serializable {
private static final long serialVersionUID = -6778920657382759194L;
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton singleton = new Singleton();
}
public static synchronized Singleton getSingleton() {
return SingletonHolder.singleton;
}
}
public class Test2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(new FileOutputStream(new File("singleton.txt")));
// 将单例对象先序列化到文本文件singleton.txt中
objectOutputStream.writeObject(Singleton.getSingleton());
objectOutputStream.close();
ObjectInputStream objectInputStream =
new ObjectInputStream(new FileInputStream(new File("singleton.txt")));
// 将文本文件singleton.txt中的对象反序列化为singleton1
Singleton singleton1 = (Singleton) objectInputStream.readObject();
objectInputStream.close();
Singleton singleton2 = Singleton.getSingleton();
// 运行结果竟打印 false !
System.out.println(singleton1 == singleton2);
}
}