在Java中,序列化是一个概念,通过它我们可以将对象的状态写入字节流,以便我们可以通过网络(使用JPA和RMI等技术)传输它。
序列化对象-确保该类实现了Serializable接口。
创建一个FileOutputStream对象,该对象表示要将对象存储到的文件的文件(抽象路径)。
通过传递上面创建的FileOutputStream对象来创建ObjectOutputStream 对象。
使用writeObject()方法将对象写入文件。
反序列化对象创建一个FileInputStream对象,该对象表示包含序列化对象的文件。
使用readObject()方法从文件中读取对象。
使用检索到的对象。
反序列化对象中的变量
当我们仅反序列化一个对象时,实例变量将被保存,并且在该过程之后将具有相同的值。
瞬态变量 - 永远不会考虑瞬态变量的值(将其从序列化过程中排除)。例如,当我们声明一个瞬态变量时,在反序列化之后,其值将始终为null,false或零(默认值)。
静态变量 - 在反序列化过程中,将不会保留静态变量的值。实际上,静态变量也不会序列化,但是因为它们属于该类。反序列化后,它们从类中获取当前值。
示例
在此程序中,我们在反序列化之前更改了实例的值,类的静态和瞬态变量。
在此过程之后,实例变量的值将相同。临时变量显示默认值,而静态变量显示类中的新(当前)值。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