ใน Java Serialization ตัวแปรที่ประกาศ transient จะ ถูกข้ามไปไม่ serialize ค่าจะกลายเป็นค่า Default (null, 0, false) หลัง Deserialize
แต่หากตัวแปรเป็น final ด้วย จะมีพฤติกรรมพิเศษ:
final+ Compile-time Constant (ค่าคงที่ที่รู้ค่าตอนคอมไพล์) -> จะถูก Serialize ตามปกติ (เพราะค่าถูก Inline เข้าไปใน Bytecode)final+ Non-constant (กำหนดค่าใน Constructor หรือ Runtime) -> จะถูกข้ามเหมือน transient ปกติ
ตัวอย่างโค้ด
import java.io.*;
class Student implements Serializable {
private String name;
private transient int age; // จะไม่ serialize
private final String school = "ABC"; // Compile-time constant -> จะ serialize
private final int id; // Non-constant final -> จะไม่ serialize (เหมือน transient)
public Student(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public void display() {
System.out.println("Name: " + name + ", Age: " + age + ", School: " + school + ", ID: " + id);
}
}
public class TransientFinalExample {
public static void main(String[] args) throws Exception {
Student s = new Student("Somchai", 20, 12345);
System.out.println("Before: ");
s.display();
// Serialize
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
oos.writeObject(s);
}
// Deserialize
Student s2;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
s2 = (Student) ois.readObject();
}
System.out.println("After: ");
s2.display();
}
}
ผลลัพธ์
Before: Name: Somchai, Age: 20, School: ABC, ID: 12345 After: Name: Somchai, Age: 0, School: ABC, ID: 0
คำอธิบาย
| Field | Modifier | Serialize? | After Deserialize |
|---|---|---|---|
| name | - | Yes | Somchai |
| age | transient | No | 0 (default int) |
| school | final + constant | Yes | ABC |
| id | final (non-constant) | No | 0 (default int) |
สรุป
transientข้ามการ serialize เสมอfinalที่เป็น Constant Expression (Primitive/String ที่กำหนดค่าตอนประกาศ) -> Serialize ได้finalที่กำหนดค่าใน Constructor/Block -> Serialize ไม่ได้ (เหมือน transient)