Java中的可序列化接口
Serializable接口存在于Java.io包中。它是一个标记界面。标记接口没有任何方法和字段。因此实现它的类不必实现任何方法。如果类希望它们的实例被序列化或反序列化,它们就会实现它。序列化是一种将对象的状态转换为字节流的机制。序列化是使用 ObjectOutputStream 完成的。反序列化是反向过程,其中字节流用于在内存中重新创建实际的Java对象。该机制用于持久化对象。反序列化是使用 ObjectInputStream 完成的。因此,它可用于使有资格将其状态保存到文件中。
宣言
public interface Serializable
示例:下面的示例显示了一个实现可序列化接口的类。
Java
// Java Program to demonstrate a class
// implementing Serializable interface
import java.io.Serializable;
public static class Student implements Serializable {
public String name = null;
public String dept = null;
public int id = 0;
}
Java
// Java program to illustrate Serializable interface
import java.io.*;
// By implementing Serializable interface
// we make sure that state of instances of class A
// can be saved in a file.
class A implements Serializable {
int i;
String s;
// A class constructor
public A(int i, String s)
{
this.i = i;
this.s = s;
}
}
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
A a = new A(20, "GeeksForGeeks");
// Serializing 'a'
FileOutputStream fos
= new FileOutputStream("xyz.txt");
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(a);
// De-serializing 'a'
FileInputStream fis
= new FileInputStream("xyz.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
A b = (A)ois.readObject(); // down-casting object
System.out.println(b.i + " " + b.s);
// closing streams
oos.close();
ois.close();
}
}
在这里,您可以看到 Student 类实现了 Serializable,但没有任何方法可以从 Serializable 实现。
示例:下面的示例代码解释了序列化和反序列化对象。
Java
// Java program to illustrate Serializable interface
import java.io.*;
// By implementing Serializable interface
// we make sure that state of instances of class A
// can be saved in a file.
class A implements Serializable {
int i;
String s;
// A class constructor
public A(int i, String s)
{
this.i = i;
this.s = s;
}
}
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
A a = new A(20, "GeeksForGeeks");
// Serializing 'a'
FileOutputStream fos
= new FileOutputStream("xyz.txt");
ObjectOutputStream oos
= new ObjectOutputStream(fos);
oos.writeObject(a);
// De-serializing 'a'
FileInputStream fis
= new FileInputStream("xyz.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
A b = (A)ois.readObject(); // down-casting object
System.out.println(b.i + " " + b.s);
// closing streams
oos.close();
ois.close();
}
}
输出:
20 GeeksForGeeks
必读: Java中的序列化和反序列化