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

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

 Serializable实际上是一个空接口java

package java.io;

public interface Serializable {
}

Serializable是一个空接口,没有什么具体内容,它的目的只是简单的标识一个类的对象能够被序列化。 什么状况下须要序列化网络

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

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

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);
	}

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

而后咱们考虑如下几个问题接口

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

问题二:假设2处serialVersionUID一致,若是A端增长一个字段,B端不变,会是什么状况呢?get

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

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

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

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

相关文章
相关标签/搜索