序列化对象

1.0   序列化对象

ObjectOutputStream 继承于OutputStream,专门用于把对象序列化到本地。提供了

public static void main(String[] args) throws IOException {
        
        Student stu = new Student("001", "大狗", 20, Gender.男);
        
        /**
         *    方案1:取stu所有的属性,通过特定的字符串(-),把各个属性值连接起来
         *  001-大狗-20-男
         */
        
        File file = new File("d:\\javatest\\l.txt");
        FileOutputStream out = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(out);
        
        oos.writeObject(stu);
        
        oos.close();
        out.close();
    }

2.0    反序列化对象

ObjectInputStream 继承于InputStream ,专门用于把本地持久化内容反序列化到内存,提供了

public static void main(String[] args) throws IOException, ClassNotFoundException {
        
        File file = new File("d:\\javatest\\l.txt");
        
        
        FileInputStream in = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(in);
        
        Student student = (Student) ois.readObject();
        System.out.println(student.getId());
        System.out.println(student.getName());
        System.out.println(student.getAge());
        System.out.println(student.getGender());
        
        ois.close();
        in.close();
    }

 

3.0   序列化版本

当序列化完成后,后期升级程序中的类(Student),此时再反序列化时会出现异常。

Exception in thread "main" java.io.InvalidClassException: cn.sxt05.serializable.Student; local class incompatible: stream classdesc serialVersionUID = -6288733824962181189, local class serialVersionUID = 1690603786167234505
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:687)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1876)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1745)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2033)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1567)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:427)
    at cn.sxt05.serializable.Test02.main(Test02.java:16)

异常原因:序列化流的serialVersionUID和升级后类的版本不匹配。

    解决方案:给Student类加序列化版本号,有两种方式

    default serial version ID 生成默认的serial version ID 一般值都是1L。

    generated serial version ID 根据当前类的属性、方法生成一个唯一ID。

public class Student implements Serializable {

    private static final long serialVersionUID = -1003763572517930507L;

4,0     transient

开发过程中,如果想忽略某些字段不让其序列化时,可以使用transient修饰。

public class Student implements Serializable {

    private static final long serialVersionUID = 7222966748321328300L;

    private String id;
    private transient String name;
    private transient int age;
    private Gender gender;
    private String phone;

 

posted on 2019-05-12 11:42  德德玛  阅读(116)  评论(0编辑  收藏  举报