问答详情
源自:6-2 transient及ArrayList源码分析

多transient属性的反序列化识别问题

请问下,自己反序列化的时候,写的是 s.readInt(); 那如果有多个transient修饰的int属性,那么怎么区别呢

提问者:sdfsdf_0001 2014-11-18 09:07

个回答

  • 好帮手慕珊
    2014-11-18 09:56:14
    已采纳

    写入顺序和读取顺序一致即可,见下面的代码,在老师代码的基础上加了一个age1属性,用transient修饰

    package com.imooc.io;


    import java.io.Serializable;


    public class Student implements Serializable{

    private String stuno;

    private String stuname;

    //该元素不会进行jvm默认的序列化,也可以自己完成这个元素的序列化

    private transient int stuage;  

    private transient int age1;

    public Student(String stuno, String stuname, int stuage,int age1) {

    super();

    this.stuno = stuno;

    this.stuname = stuname;

    this.stuage = stuage;

    this.age1=age1;

    }


    public String getStuno() {

    return stuno;

    }

    public int getAge1() {

    return age1;

    }


    public void setAge1(int age1) {

    this.age1 = age1;

    }


    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 + ",age1="+age1+"]";

    }

    private void writeObject(java.io.ObjectOutputStream s)

           throws java.io.IOException{

    s.defaultWriteObject();//把jvm能默认序列化的元素进行序列化操作

    s.writeInt(stuage);//自己完成stuage的序列化

    s.writeInt(age1);

    }

    private void readObject(java.io.ObjectInputStream s)

           throws java.io.IOException, ClassNotFoundException{

     s.defaultReadObject();//把jvm能默认反序列化的元素进行反序列化操作

     this.stuage = s.readInt();//自己完成stuage的反序列化操作

     this.age1=s.readInt();

    }

    }