transient 与 Java 序列化中的 final 如何协同工作?
在 Java 中,序列化是一种概念,我们可以使用它将对象的 state 写入到字节流中,以便我们可以通过网络传输(使用类似 JPA 和 RMI 的技术)。
Transient 变量 − Transient 变量的值永远不会被考虑(它们从序列化流程中被排除)。也就是说,当我们声明一个变量是 transient 时,在反序列化后它的值始终为 null、false 或零(默认值)。
因此,在对类的对象进行序列化时,如果你希望 JVM 忽略特定的实例变量,你需要将其声明为 transient。
public transient int limit = 55; // will not persist public int b; // will persist
示例
在以下 java 程序中,Student 类有两个实例变量:name 和 age,其中 age 被声明为 transient。在另一个名为 SerializeExample 的类中,我们尝试对 Student 对象进行序列化和反序列化,并显示它的实例变量。由于 age 是不可见的(transient),所以只显示 name 值。
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;
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);
}
}
public class SerializeExample {
public static void main(String args[]) throws Exception {
//Creating a Student object
Student std = new Student("Sarmista", 27);
//Serializing the object
FileOutputStream fos = new FileOutputStream("e:\student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close();
fos.close();
System.out.println("Values before de-serialization: ");
std.display();
System.out.println("Object serialized.......");
//De-serializing the object
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("Values after de-serialization");
deSerializedStd.display();
}
}输出
Values before de-serialization: Name: Sarmista Age: 27 Object serialized....... Object de-serialized....... Values after de-serialization Name: Sarmista Age: 0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP