java中的transient關鍵字
阿新 • • 發佈:2019-01-08
transient
transient是型別修飾符,只能用來修飾字段。在物件序列化的過程中,標記為transient的變數不會被序列化。
序列化和反序列化
一個物件的表示轉化為位元組流的過程稱為序列化(serialization),從位元組流中把物件重建出來稱為反序列化反序列化(deserialization)。
測試程式碼
public class TestTransient {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
A a = new A(25, "測試");
System.out.println(a);
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("/Users/dev/Desktop/tmp/a.txt"));
oos.writeObject(a);
oos.close();
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("/Users/dev/Desktop/tmp/a.txt"));
a = (A) ois.readObject();
System.out.println(a);
}
static class A implements Serializable {
int a;
transient String b;
public A(int a, String b) {
this.a = a;
this.b = b;
}
public String toString () {
return "a = " + a + ",b = " + b;
}
}
}
輸出結構
a = 25,b = 測試
a = 25,b = null