กราฟอ็อบเจ็กต์ประกอบด้วยชุดของออบเจ็กต์ที่ได้รับการซีเรียลไลซ์โดยอัตโนมัติโดยที่อ็อบเจ็กต์ที่มีการอ้างอิงนั้นจะถูกทำให้เป็นอนุกรมด้วย ออบเจ็กต์ใด ๆ ที่ถูกทำให้เป็นอนุกรมและมีอ็อบเจกต์อ้างอิง การอ้างอิงอ็อบเจ็กต์จะถูกทำให้เป็นอนุกรมโดย JVM
ตัวอย่าง
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class One implements Serializable{
Two s2 = new Two();
}
class Two implements Serializable{
Three s3 = new Three();
}
class Three implements Serializable{
int i = 34;
int j = 67;
}
public class Demo_Serialize{
public static void main(String args[]) throws Exception{
One s1 = new One();
FileOutputStream my_fos = new FileOutputStream("abc.ser");
ObjectOutputStream my_oos = new ObjectOutputStream(my_fos);
my_oos.writeObject(s1);
my_fos.close();
my_oos.close();
FileInputStream my_fis = new FileInputStream("abc.ser");
ObjectInputStream my_ois = new ObjectInputStream(my_fis);
One my_obj = (One) my_ois.readObject();
my_fis.close();
my_ois.close();
System.out.println("Value of i after it is serialized is " + my_obj.s2.s3.i);
System.out.println("Value of j after it is serialized is "+my_obj.s2.s3.j);
}
} ผลลัพธ์
Value of i after it is serialized is 34 Value of j after it is serialized is 67
คลาสที่ชื่อ 'หนึ่ง' สืบทอดมาจากคลาส 'ซีเรียลไลซ์ได้' ที่นี่ อีกตัวอย่างหนึ่งของคลาสที่แตกต่างกันถูกสร้างขึ้น คลาสเดียวกันนั้นสืบทอดมาจากคลาส 'Serializable' อีกครั้ง อินสแตนซ์อื่นจะถูกสร้างขึ้นภายในคลาสนี้
คลาสอื่นสืบทอดคลาส 'Serializable' ในที่นี้ มีการกำหนดจำนวนเต็มสองจำนวน และสร้างคลาสอีกชื่อหนึ่งว่า 'Demo_Serialize' ในที่นี้ ฟังก์ชันหลักถูกกำหนดไว้แล้ว อินสแตนซ์ของคลาสแรกที่กำหนดไว้ และอินสแตนซ์ของ FileOutputStream และ ObjectOutputStream จะถูกสร้างขึ้น ออบเจ็กต์เขียนโดยใช้สตรีมเหล่านี้ ต่อมาปิดลำธาร สิ่งนี้ทำอีกครั้งเพื่อทำให้ข้อมูลเป็นอนุกรม เอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล