Java transient关键字与序列化操作实例详解
本文实例讲述了Javatransient关键字与序列化操作。分享给大家供大家参考,具体如下:
一介绍
transient关键字不会进行JVM虚拟机的序列化,但也可以自己进行序列化,要用到下面两个函数。这两个函数来自ArrayList源码,可以分析ArrayList源码的序列化和反序列化问题。这样做可以对有效元素进行序列化,不对无效元素进行序列化,以提高网络传输性能。
privatevoidwriteObject(java.io.ObjectOutputStreams)throwsjava.io.IOException privatevoidreadObject(java.io.ObjectInputStreams)throwsjava.io.IOException,ClassNotFoundException
二实例
packagecom.imooc.io;
importjava.io.Serializable;
publicclassStudentimplementsSerializable{
privateStringstuno;
privateStringstuname;
//该元素不会进行jvm默认的序列化
privatetransientintstuage;
publicStudent(Stringstuno,Stringstuname,intstuage){
super();
this.stuno=stuno;
this.stuname=stuname;
this.stuage=stuage;
}
publicStringgetStuno(){
returnstuno;
}
publicvoidsetStuno(Stringstuno){
this.stuno=stuno;
}
publicStringgetStuname(){
returnstuname;
}
publicvoidsetStuname(Stringstuname){
this.stuname=stuname;
}
publicintgetStuage(){
returnstuage;
}
publicvoidsetStuage(intstuage){
this.stuage=stuage;
}
@Override
publicStringtoString(){
return"Student[stuno="+stuno+",stuname="+stuname+",stuage="
+stuage+"]";
}
}
packagecom.imooc.io;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
publicclassObjectSeriaDemo1{
publicstaticvoidmain(String[]args)throwsException{
Stringfile="demo/obj.dat";
//1.对象的序列化
ObjectOutputStreamoos=newObjectOutputStream(
newFileOutputStream(file));
Studentstu=newStudent("10001","张三",20);
oos.writeObject(stu);
oos.flush();
oos.close();
ObjectInputStreamois=newObjectInputStream(
newFileInputStream(file));
Studentstu1=(Student)ois.readObject();
System.out.println(stu1);
ois.close();
}
}
三运行结果
Student[stuno=10001,stuname=张三,stuage=0]
更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。