1. 程式人生 > >transient關鍵字與物件的屬性不被序列化

transient關鍵字與物件的屬性不被序列化

當某個物件的屬性不希望被序列化時,可以使用transient關鍵字進行宣告

import java.io.Serializable ;
public class Person implements Serializable{
private transient String name ;// 宣告name屬性,但是此屬性不被序列化
private int age ;// 宣告age屬性
public Person(String name,int age){// 通過構造設定內容
this.name = name ;
this.age = age ;
}
public String toString(){// 覆寫toString()方法
return "姓名:" + this.name + ";年齡:" + this.age ;
}
};

import java.io.File ;
import java.io.IOException ;
import java.io.FileOutputStream ;
import java.io.OutputStream ;
import java.io.ObjectOutputStream ;
import java.io.FileInputStream ;
import java.io.InputStream ;
import java.io.ObjectInputStream ;
public class SerDemo04{
public static void main(String args[]) throws Exception{
ser() ;
dser() ;
}
public static void ser() throws Exception {
File f = new File("D:" + File.separator + "test.txt") ;// 定義儲存路徑
ObjectOutputStream oos = null ;// 宣告物件輸出流
OutputStream out = new FileOutputStream(f) ;// 檔案輸出流
oos = new ObjectOutputStream(out) ;
oos.writeObject(new Person("張三",30)) ;// 儲存物件
oos.close() ; // 關閉
}
public static void dser() throws Exception {
File f = new File("D:" + File.separator + "test.txt") ;// 定義儲存路徑
ObjectInputStream ois = null ;// 宣告物件輸入流
InputStream input = new FileInputStream(f) ;// 檔案輸入流
ois = new ObjectInputStream(input) ;// 例項化物件輸入流
Object obj = ois.readObject() ;// 讀取物件
ois.close() ; // 關閉
System.out.println(obj) ;
}
};

執行結果:

姓名:null;年齡:30