您好,登錄后才能下訂單哦!
本文實(shí)例講述了Java transient關(guān)鍵字與序列化操作。分享給大家供大家參考,具體如下:
一 介紹
transient關(guān)鍵字不會(huì)進(jìn)行JVM虛擬機(jī)的序列化,但也可以自己進(jìn)行序列化,要用到下面兩個(gè)函數(shù)。這兩個(gè)函數(shù)來自ArrayList源碼,可以分析ArrayList源碼的序列化和反序列化問題。這樣做可以對(duì)有效元素進(jìn)行序列化,不對(duì)無效元素進(jìn)行序列化,以提高網(wǎng)絡(luò)傳輸性能。
private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException
二 實(shí)例
package com.imooc.io; import java.io.Serializable; public class Student implements Serializable{ private String stuno; private String stuname; //該元素不會(huì)進(jìn)行jvm默認(rèn)的序列化 private transient int stuage; public Student(String stuno, String stuname, int stuage) { super(); this.stuno = stuno; this.stuname = stuname; this.stuage = stuage; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getStuname() { return stuname; } public void setStuname(String stuname) { this.stuname = stuname; } public int getStuage() { return stuage; } public void setStuage(int stuage) { this.stuage = stuage; } @Override public String toString() { return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage=" + stuage + "]"; } }
package com.imooc.io; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ObjectSeriaDemo1 { public static void main(String[] args) throws Exception{ String file = "demo/obj.dat"; //1.對(duì)象的序列化 ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(file)); Student stu = new Student("10001", "張三", 20); oos.writeObject(stu); oos.flush(); oos.close(); ObjectInputStream ois = new ObjectInputStream( new FileInputStream(file)); Student stu1 = (Student)ois.readObject(); System.out.println(stu1); ois.close(); } }
三 運(yùn)行結(jié)果
Student [stuno=10001, stuname=張三, stuage=0]
更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。