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

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

 Serializable其实是一个空接口

package java.io;

public interface Serializable {
}

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

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

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

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

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的作用和用法

原文地址:https://www.cnblogs.com/zcy_soft/p/4617396.html