zoukankan      html  css  js  c++  java
  • 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的作用和用法

  • 相关阅读:
    HYSBZ 3813 奇数国
    HYSBZ 4419 发微博
    HYSBZ 1079 着色方案
    HYSBZ 3506 排序机械臂
    HYSBZ 3224 Tyvj 1728 普通平衡树
    Unity 3D,地形属性
    nginx 的naginx 种包含include关键字
    Redis 出现NOAUTH Authentication required解决方案
    mysql 8.0出现 Public Key Retrieval is not allowed
    修改jar包里的源码时候需要注意的问题
  • 原文地址:https://www.cnblogs.com/zcy_soft/p/4617396.html
Copyright © 2011-2022 走看看