What is Java serialization and how is it implemented?
Java serialization is the process of converting an object into a byte stream, allowing the object to be transmitted over a network or stored in a file.
In Java, the way to implement serialization is to have a class implement the Serializable interface. The Serializable interface is an empty interface with no method definitions. It serves as a marker interface to indicate that the class can be serialized.
To achieve serialization, you just need to add the statement “implements Serializable” in the class definition. For example:
public class MyClass implements Serializable {
// 类的定义
}
Classes that implement the Serializable interface can be serialized and deserialized using Java’s serialization mechanism. Serialization involves converting objects into byte streams using the writeObject method of the ObjectOutputStream class, while deserialization involves converting byte streams back into objects using the readObject method of the ObjectInputStream class.
Here is a simple example of serialization and deserialization:
import java.io.*;
public class Main {
public static void main(String[] args) {
// 序列化对象
MyClass myObject = new MyClass();
try {
FileOutputStream fileOut = new FileOutputStream("myobject.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(myObject);
out.close();
fileOut.close();
System.out.println("Object serialized successfully");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化对象
MyClass deserializedObject = null;
try {
FileInputStream fileIn = new FileInputStream("myobject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedObject = (MyClass) in.readObject();
in.close();
fileIn.close();
System.out.println("Object deserialized successfully");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 使用反序列化后的对象进行操作
if (deserializedObject != null) {
deserializedObject.doSomething();
}
}
}
class MyClass implements Serializable {
public void doSomething() {
System.out.println("Doing something...");
}
}