21xrx.com
2024-09-19 09:25:20 Thursday
登录
文章检索 我的文章 写文章
Java Serializable的使用及作用
2023-06-14 21:17:02 深夜i     --     --
Java Serializable

在Java中,Serializable接口是一个标记接口,用于标记类是否可以序列化。当一个类实现了Serializable接口后,就可以将该类的对象序列化为字节流,存储在文件中或通过网络传输到远程服务器。同时,该类的对象也可以反序列化为普通对象,重新恢复其状态。因此,Serializable接口在Java的分布式系统、多线程通信、对象持久化等场景中,有着重要的作用。

下面是一个简单的示例代码:


import java.io.*;

public class Student implements Serializable {

  private String name;

  private int age;

  

  public Student(String name, int age)

    this.name = name;

    this.age = age;

  

  

  public String getName()

    return name;

  

  

  public int getAge()

    return age;

  

  

  public void setName(String name)

    this.name = name;

  

  

  public void setAge(int age)

    this.age = age;

  

}

public class SerializeTest {

  public static void main(String[] args) {

    Student student = new Student("Tom", 18);

    FileOutputStream fos = null;

    ObjectOutputStream oos = null;

    try {

      fos = new FileOutputStream("student.txt");

      oos = new ObjectOutputStream(fos);

      oos.writeObject(student);

      System.out.println("序列化成功");

    } catch (IOException e) {

      e.printStackTrace();

    } finally {

      try {

        if (oos != null) {

          oos.close();

        }

        if (fos != null) {

          fos.close();

        }

      } catch (IOException e) {

        e.printStackTrace();

      }

    }

  }

}

上述代码中,我们定义了一个Student类,实现了Serializable接口,可以进行序列化和反序列化操作。在main方法中,我们将一个Student对象序列化为字节流,存储在student.txt文件中。运行程序后,可以看到输出结果为“序列化成功”。

、序列化、反序列化。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复