Trong Java, serialization là quá trình ghi trạng thái đối tượng thành byte stream để truyền qua mạng (RMI, JPA, v.v.).
Biến transient
Giá trị của biến transient không được serialize. Sau khi deserialize, giá trị sẽ là mặc định: null (object), false (boolean), 0 (number).
public transient int limit = 55; // sẽ KHÔNG được persist public int b; // sẽ được persist
Ví dụ: Transient với final
import java.io.*;
class Student implements Serializable {
private String name;
private transient int age; // transient
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 {
Student std = new Student("Sarmista", 27);
// Serialize
FileOutputStream fos = new FileOutputStream("e:\\student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close(); fos.close();
System.out.println("Object serialized.......");
// Deserialize
FileInputStream fis = new FileInputStream("e:\\student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student deSerializedStd = (Student) ois.readObject();
ois.close(); fis.close();
System.out.println("Values after de-serialization");
deSerializedStd.display();
}
}
Kết quả
Values before de-serialization: Name: Sarmista Age: 27 Object serialized....... Object de-serialized....... Values after de-serialization Name: Sarmista Age: 0
Lưu ý quan trọng về transient final:
- Nếu biến
transient finalđược khởi tạo tại chỗ declaration với compile-time constant (hằng số biên dịch), nó vẫn được serialize vì compiler inline giá trị. - Nếu khởi tạo trong constructor hoặc không phải compile-time constant, nó không được serialize và sẽ nhận giá trị mặc định sau deserialize.
transient final int a = 10; // Serialize (compile-time constant) transient final int b = someMethod(); // KHÔNG serialize transient final int c; c = 20; // KHÔNG serialize