serialVersionUID, ObjectInputStream与ObjectOutputStream类,Serializable接口,serialVersionUID的作用和用法

ObjectInputStream与ObjectOutputStream类所读写的对象必须实现Serializable接口,对象中的transient和static类型成员变量不会被读取和写入

 Serializable其实是一个空接口

1
2
3
4
package java.io;
 
public interface Serializable {
}

Serializable是一个空接口,没有什么具体内容,它的目的只是简单的标识一个类的对象可以被序列化。 什么情况下需要序列化

a)当你想把的内存中的对象写入到硬盘的时候;

b)当你想用套接字在网络上传送对象的时候;

c)当你想通过RMI传输对象的时候; 再稍微解释一下:a)比如说你的内存不够用了,那计算机就要将内存里面的一部分对象暂时的保存到硬盘中,等到要用的时候再读入到内存中,硬盘的那部分存储空间就是所谓的虚拟内存。在比如过你要将某个特定的对象保存到文件中,我隔几天在把它拿出来用,那么这时候就要实现Serializable接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public static void main(String args[]) throws Exception {
 
        class Student implements Serializable {
 
            private static final long serialVersionUID = 0xbc9903f7986df52fL;
 
            String name;
            int id ;
            int age;
            String department;
            public Student(String name, int id, int age, String department) {
                this.age = age;
                this.department = department;
                this.id = id;
                this.name = name;
            }
        }
 
        Student s1=new Student("张2三", 1, 5, "化学");
        Student s2=new Student("李四1", 2, 9, "生物");
 
        FileOutputStream fout = new FileOutputStream("C:\\student.txt");
        ObjectOutputStream out=new ObjectOutputStream(fout);
        out.writeObject(s1);
        out.writeObject(s2);
        out.close();
        FileInputStream fin=new FileInputStream("C:\\student.txt");
        ObjectInputStream in=new ObjectInputStream(fin);
        try {
            s1=(Student) in.readObject();
            s2=(Student) in.readObject();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        in.close();
        System.out.print("name:"+s1.name);
        System.out.print(" id:"+s1.id);
        System.out.print(" age:"+s1.age);
        System.out.println(" department:"+s1.department);
        System.out.print("name:"+s2.name);
        System.out.print(" id:"+s2.id);
        System.out.print(" age:"+s2.age);
        System.out.println(" department:"+s2.department);
    }

上面就是一个序列化反序列化的例子

然后我们考虑以下几个问题

问题一:假设有A端和B端,如果2处的serialVersionUID不一致,会产生什么错误呢?

问题二:假设2处serialVersionUID一致,如果A端增加一个字段,B端不变,会是什么情况呢?

问题三:假设2处serialVersionUID一致,如果B段增加一个字段,A端不变,会是什么情况呢?

问题四:假设2处serialVersionUID一致,如果A端减少一个字段,B端不变,会是什么情况呢?

问题五:假设2处serialVersionUID一致,如果B端减少一个字段,A端不变,会是什么情况呢?

引出问题:serialVersionUID的作用和用法

posted @   春哥也编程  阅读(941)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示