Java 序列化概念和示例
原文: https://javabeginnerstutorial.com/core-java-tutorial/java-serialization-concept-example/
在这里,我将学习和教你什么是 Java 的序列化以及如何编写相同的代码。
什么是序列化
Java 序列化是一个过程,其中对象的当前状态将保存在字节流中。 字节流是平台无关的,因此一旦在一个系统中创建了对象,便可以在其他平台上反序列化。
序列化有什么用
如上所述,序列化会将对象状态转换为字节流。 该字节流可用于其他目的。
- 写入磁盘
- 存储在内存中
- 通过网络将字节流发送到其他平台
- 将字节流保存在 DB 中(作为 BLOB)
Java 中的序列化和反序列化
现在我们知道什么是序列化了。 但是我们需要了解如何用 Java 实现它以及它如何工作。
Java 已经提供了开箱即用的方式(java.io.Serializable接口)来序列化对象。 如果要序列化任何类,则该类需要实现给定的接口。
注:Serializable接口是标记接口。 因此,Serializable接口中没有任何方法。
Java 类序列化代码
Employee.java
package com.jbt;import java.io.Serializable;public class Employee implements Serializable{public String firstName;public String lastName;private static final long serialVersionUID = 5462223600l;}
SerializaitonClass.java
package com.jbt;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;public class SerializaitonClass {public static void main(String[] args) {Employee emp = new Employee();emp.firstName = "Vivekanand";emp.lastName = "Gautam";try {FileOutputStream fileOut = new FileOutputStream("./employee.txt");ObjectOutputStream out = new ObjectOutputStream(fileOut);out.writeObject(emp);out.close();fileOut.close();System.out.printf("Serialized data is saved in ./employee.txt file");} catch (IOException i) {i.printStackTrace();}}}
DeserializationClass.java
package com.jbt;import java.io.*;public class DeserializationClass {public static void main(String[] args) {Employee emp = null;try {FileInputStream fileIn = new FileInputStream("./employee.txt");ObjectInputStream in = new ObjectInputStream(fileIn);emp = (Employee) in.readObject();in.close();fileIn.close();} catch (IOException i) {i.printStackTrace();return;} catch (ClassNotFoundException c) {System.out.println("Employee class not found");c.printStackTrace();return;}System.out.println("Deserializing Employee...");System.out.println("First Name of Employee: " + emp.firstName);System.out.println("Last Name of Employee: " + emp.lastName);}}
首先,运行“SerializaitonClass”,您将创建“employee.txt”文件。
第二次运行“DeserializationClass”,Java 将反序列化该类,并在控制台中显示该值。
输出将是
Deserializing Employee...First Name of Employee: VivekanandLast Name of Employee: Gautam
项目要点
- 序列化接口需要使对象序列化。
- 瞬态实例变量并未以对象状态序列化。
- 如果超类实现了
Serializable,则子类也可以自动进行Serializable。 - 如果无法对超类进行序列化,则在对子类进行反序列化时,将调用超类的默认构造器。 因此,所有变量将获得默认值,引用将为
null。
在下一篇文章中,我们将讨论瞬态变量的使用。
