Từ khoá transient key trong Java hay @Transient trong kotlin dùng cho các property, các property sẽ không được áp dụng quá trình serialization ( quá trình convert object thành 1 dòng byte và lưu vào file).
II, Ví dụ
Ví dụ 1: Bạn có Student có 3 property: id, name và age. Khi 1 instance của Student tiến hành quá trình serialization, bạn muốn age bị bỏ qua trong quá trình đó
1 2 3 4 5 6 7 8 9 10 11 12
publicclassStudentimplementsSerializable{
privateint id; private String name; privatetransientint age; //Now it will not be serialized
Tiếp theo, chúng ta viết code thực hiện quá trình serialization để convert object thành 1 dòng byte và lưu vào file:
1 2 3 4 5 6 7 8 9 10 11 12 13
classPersistExample{
publicstaticvoidmain(String args[]){ Student s1 = new Student(211, "ravi", 22); //writing object into file FileOutputStream f = new FileOutputStream("f.txt"); ObjectOutputStream out = new ObjectOutputStream(f); out.writeObject(s1); out.flush(); out.close(); f.close(); } }
Cuối cùng, chúng ta thực hiện quá trình de-serialization để phục hồi object từ file và in ra dữ liệu của object đó:
1 2 3 4 5 6 7 8 9
classDePersist{
publicstaticvoidmain(String args[]){ ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt")); Student s = (Student)in.readObject(); System.out.println(s.id + " " + s.name + " " + s.age); in.close(); } }
Chúng ta đánh dấu age là 1 transient variable nên nó sẽ không được serialize vào file. Do đó chúng ta có kết quả: