Tìm hiểu về transient
2020-07-01 Java, Kotlin
I, Transient keyword
- 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 | public class Student implements Serializable { private int id; private String name; private transient int age; //Now it will not be serialized public Student[int id, String name,int age] { this.id = id; this.name = name; this.age=age; } } |
- 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 | class PersistExample{ public static void main[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 | class DePersist{ public static void main[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ả:
1 | 211 ravi 0 |