欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

transient关键字与序列化

程序员文章站 2022-04-04 09:11:55
...
一 介绍
transient关键字不会进行JVM虚拟机的序列化,但也可以自己进行序列化,要用到下面两个函数。这两个函数来自ArrayList源码,可以分析ArrayList源码的序列化和反序列化问题。这样做可以对有效元素进行序列化,不对无效元素进行序列化,以提高网络传输性能。
private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException
 
二 实例
package com.imooc.io;
 
import java.io.Serializable;
 
public class Student implements Serializable{
    private String stuno;
    private String stuname;
    //该元素不会进行jvm默认的序列化
    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.对象的序列化
         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(); 
    }
}
 
三 运行结果
Student [stuno=10001, stuname=张三, stuage=0]

 

 
相关标签: transient 序列化