1. 所有实现序列化的类都必须实现 Serializable 接口,序列化有如下两个特点:
2. 序列化和反序列化的实例
- package StreamLearn;
- import java.io.*;
- /**
- * Created by liujinhong on 2017/3/6.
- */
- /**
- * 序列化和返序列化实例
- */
- public class SerialObjectTest {
- public static void main(String[] args) {
- People p = new People();
- ObjectOutputStream oos = null;
- ObjectInputStream ois = null;
- //序列化
- try {
- FileOutputStream fos = new FileOutputStream("/Users/liujinhong/Desktop/test/ttt");
- oos = new ObjectOutputStream(fos);
- oos.writeObject(p);
- } catch (Exception e) {
- System.out.println(e);
- } finally {
- }
- //反序列化
- People p1;
- try {
- FileInputStream fis = new FileInputStream("/Users/liujinhong/Desktop/test/ttt");
- ois = new ObjectInputStream(fis);
- p1 = (People) ois.readObject();
- System.out.println(p1.a);
- System.out.println(p1.b);
- System.out.println(p1.book.id);
- } catch (Exception e) {
- System.out.println(e);
- } finally {
- }
- }
- }
- class People implements Serializable {
- public int a = 1;
- public transient int b = 2;
- public Book book = new Book();
- }
- class Book implements Serializable {
- public int id = 1;
- }
3. 什么情况下需要使用序列化?
4. serialVersionUID 作用?
在序列化和反序列化的过程中,serialVersionUID 起着非常重要的作用,每一个类都有一个特定的 serialVersionUID,在反序列化的过程中通过 serialVersionUID 来判断类的兼容性。如果不兼容会跑出 InvalidClassException 异常。
5. 自定义 serialVersionUID 的优点?
来源: http://www.bubuko.com/infodetail-1970717.html