21xrx.com
2025-03-30 15:45:18 Sunday
文章检索 我的文章 写文章
Java中的Serializable接口详解及代码案例
2023-06-16 22:12:23 深夜i     21     0
Serializable接口 序列化 版本号

Java中的Serializable接口是用来实现对象的序列化,将实现了Serializable接口的对象转换成数据流,方便在网络传输或本地存储。在Java的IO流操作中,这个接口常被使用到。

实现Serializable接口的类需要注意事项:

1. 若继承类也需要被序列化,则也必须实现Serializable接口,否则会出现NotSerializableException异常。

2. 在设计时需要考虑数据兼容性,因为被序列化的对象可能会被存储一段时间或者在使用过程中被传输到其他的系统中。因此,当修改了序列化类的属性时,需要使用serialVersionUID版本号来保证不会出现版本不匹配的问题。

下面是一个简单的Serializable接口的应用案例:

JAVA
import java.io.*;
public class SerializableExample implements Serializable {
  private static final long serialVersionUID = 1L;
  private String name;
  private int age;
  public SerializableExample(String name, int age) {
    super();
    this.name = name;
    this.age = age;
  }
  public String getName()
    return name;
  
  public int getAge()
    return age;
  
  public static void main(String[] args) throws Exception {
    //序列化过程
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.txt"));
    SerializableExample se = new SerializableExample("Tom", 22);
    oos.writeObject(se);
    oos.flush();
    oos.close();
    //反序列化过程
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
    SerializableExample se2 = (SerializableExample)ois.readObject();
    System.out.println("name : "+se2.getName()+"  age : "+se2.getAge());
    ois.close();
  }
}

程序输出结果:

name : Tom  age : 22

使用Serializable接口,程序成功将对象序列化到了本地文件中,并且反序列化后成功还原成了原有的对象。

  
  

评论区