Serialization แปลงสถานะอ็อบเจกต์เป็น Byte Stream อ็อบเจกต์ serialize ได้หากคลาส implements Serializable หรือ Externalizable Deserialization แปลง byte stream กลับเป็นอ็อบเจกต์
ใช้ transient ป้องกันไม่ให้ serialize ตัวแปรนั้น (จะเก็บค่าเริ่มต้น: 0, 0.0, false, null) ใช้ FileOutputStream และ ObjectOutputStream สำหรับ serialize
ตัวอย่าง: Serialize และ Deserialize
import java.io.*;
public class SerializationTest implements Serializable {
int a = 1, b = 2;
transient int c = 3; // ไม่ serialize
public static void main(String[] args) throws Exception {
SerializationTest obj = new SerializationTest();
// Serialization
FileOutputStream fos = new FileOutputStream("serialization.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
// Deserialization
FileInputStream fis = new FileInputStream("serialization.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
SerializationTest test = (SerializationTest) ois.readObject();
System.out.println("a = " + test.a); // 1
System.out.println("b = " + test.b); // 2
System.out.println("c = " + test.c); // 0 (transient -> default value)
}
}
ผลลัพธ์
a = 1
b = 2
c = 0
สำคัญ: transient variable จะได้ค่า default หลัง deserialize (int=0, double=0.0, boolean=false, object=null) ต้องมี serialVersionUID สำหรับ version control