乐闻世界logo
搜索文章和话题

What is Serialization in Java?

1个答案

1

In Java, serialization is the process of converting an object's state into a sequence of bytes, which can then be persisted or transmitted over a network. When the receiver needs it, these bytes can be reassembled into the original object, a process known as deserialization.

Serialization in Java is primarily achieved by implementing the java.io.Serializable interface. This interface is a marker interface containing no methods and is solely used to indicate that an object of a class can be serialized.

Serialization Use Cases:

  1. Persistence: Applications can serialize objects to disk for later retrieval and restoration of their state.
  2. Remote Communication: When transmitting objects between a client and server over a network, serializing the objects into a byte stream enables their transmission.
  3. Deep Copy: Creating a deep copy of an object through serialization and deserialization.

Example:

Assume a Student class defined as follows:

java
import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } // Getter and Setter methods public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

We can serialize and deserialize this Student object as follows:

java
import java.io.*; public class SerializationExample { public static void main(String[] args) { Student student = new Student("John Doe", 22); // Serialization try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.ser"))) { out.writeObject(student); } catch (IOException e) { e.printStackTrace(); } // Deserialization try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.ser"))) { Student deserializedStudent = (Student) in.readObject(); System.out.println("Student Name: " + deserializedStudent.getName()); System.out.println("Student Age: " + deserializedStudent.getAge()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }

In this example, we first create a Student object, serialize it, and store it in a file named "student.ser". Subsequently, we deserialize the object from this file and print the student's information to confirm that the object's state has been successfully restored.

2024年8月16日 00:54 回复

你的答案