ใน Java การทำให้เป็นอันดับเป็นแนวคิดที่ใช้ซึ่งเราสามารถเขียนสถานะของอ็อบเจ็กต์ลงในสตรีมไบต์เพื่อให้เราสามารถถ่ายโอนผ่านเครือข่าย (โดยใช้เทคโนโลยีเช่น JPA และ RMI)
ตัวแปรชั่วคราว − ค่าของตัวแปรชั่วคราวจะไม่ถูกพิจารณา (ค่าเหล่านี้ไม่รวมอยู่ในกระบวนการซีเรียลไลซ์เซชั่น) กล่าวคือ เมื่อเราประกาศตัวแปรชั่วคราว หลังจากการดีซีเรียลไลซ์เซชัน ค่าจะเป็นโมฆะ เท็จ หรือศูนย์เสมอ (ค่าเริ่มต้น)
ดังนั้น ในขณะที่ทำให้เป็นอนุกรมอ็อบเจ็กต์ของคลาส หากคุณต้องการให้ JVM ละเลยตัวแปรอินสแตนซ์เฉพาะ คุณต้องประกาศให้เป็นแบบชั่วคราว
public transient int limit = 55; // will not persist public int b; // will persist
ตัวอย่าง
ในโปรแกรมจาวาต่อไปนี้ คลาส Student มีตัวแปรอินสแตนซ์สองชื่อและอายุ โดยที่อายุถูกประกาศชั่วคราว ในคลาสอื่นชื่อ SerializeExample เรากำลังพยายามทำให้เป็นอนุกรมและฆ่าเชื้อวัตถุ Student และแสดงตัวแปรอินสแตนซ์ของมัน เนื่องจากอายุถูกทำให้มองไม่เห็น (ชั่วคราว) จึงแสดงเฉพาะค่าชื่อเท่านั้น
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