一個對象只要實現了Serilizable接口,這個對象就可以被序列化,java的這種序列化模式為開發者提供了很多便利,我們可以不必關系具體序列化的過程,只要這個類實現了Serilizable接口,這個的所有屬性和方法都會自動序列化。
如果我們一個實現Serilizable接口的類中的某個屬性不需要序列化,可以用 transient類標識這個屬性,這樣這個屬性在反序列化是并不會被加載進來,例如
public class TestTransient {
/*** @param args* @throws IOException * @throws FileNotFoundException * @throws ClassNotFoundException */public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { A a = new A(25,"張三"); System.out.PRintln(a); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://mm.txt")); oos.writeObject(a); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c://mm.txt")); a = (A)ois.readObject(); System.out.println(a);
}
}
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
在上面的例子中,我將屬性b前添加關鍵字transient,我們看到雖然我們序列化的對象a的屬性值為“張三”,但是當我們反序列化之后發現這個屬性為空,說明這個屬性沒有進行序列化新聞熱點
疑難解答