在Java中,序列化是一个概念,通过它我们可以将对象的状态写入字节流,以便我们可以通过网络(使用JPA和RMI等技术)传输它。
序列化对象-
确保该类实现了Serializable接口。
创建一个FileOutputStream对象,该对象表示要将对象存储到的文件的文件(抽象路径)。
通过传递上面创建的FileOutputStream对象来创建ObjectOutputStream 对象。
使用writeObject()方法将对象写入文件。
反序列化对象
创建一个FileInputStream对象,该对象表示包含序列化对象的文件。
使用readObject()方法从文件中读取对象。
使用检索到的对象。
甲构造 是类似的方法和它在时间创建的类的对象调用时,它通常被用来初始化一个类的实例的变量。构造函数与其类具有相同的名称,并且没有返回类型。
如果不提供构造函数,则编译器将代表您定义一个构造函数,该构造函数将使用默认值初始化实例变量。
当我们反序列化一个对象时,永远不会调用其类的构造函数。考虑下面的示例,这里有一个名为Student的类,带有两个实例变量和一个默认构造函数(使用两个硬编码值初始化)和一个参数化构造函数。
此类的display()方法显示当前实例的变量值。
我们通过传递两个值(vani和27)并对其进行序列化来创建Student类的对象。
当我们反序列化此对象并调用display()方法时,将打印我们传递的值。静态变量会打印该类中的新(当前)值。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Student implements Serializable{ private String name; private transient int age; private static int year = 2018; public Student(){ System.out.println("This is a constructor"); this.name = "Krishna"; this.age = 25; } public Student(String name, int age){ this.name = name; this.age = age; } public void display() { System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Year: "+Student.year); } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setYear(int year) { Student.year = year; } } public class SerializeExample{ public static void main(String args[]) throws Exception{ //创建 Student 对象 Student std = new Student("Vani", 27); //序列化对象 FileOutputStream fos = new FileOutputStream("e:\\student.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(std); oos.close(); fos.close(); //在反序列化之前打印数据 System.out.println("反序列化前的值"); std.display(); //更改静态变量值 std.setYear(2019); //更改实例变量值 std.setName("Varada"); //更改瞬态变量值 std.setAge(19); System.out.println("Object serialized......."); //反序列化对象 FileInputStream fis = new FileInputStream("e:\\student.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Student deSerializedStd = (Student) ois.readObject(); System.out.println("Object de-serialized......."); ois.close(); fis.close(); System.out.println("反序列化后的值"); deSerializedStd.display(); } }
输出结果
反序列化前的值 Name: Vani Age: 27 Year: 2018 Object serialized....... Object de-serialized....... 反序列化后的值 Name: Vani Age: 0 Year: 2019