Create an Object Using Serialization and Deserialization
Creating an object using serialization and deserialization is a way of creating an object that requires the class to be serializable. In the following example, we create an object of a Student
class called newStudent
using serialization and deserialization.
import java.io.Serializable;
class Student implements Serializable {
private String name;
private int id;
}
public class Main {
public static void main(String[] args) throws Exception {
//Creating an object
Student student = new Student();
student.name = "John";
student.id = 123;
//Serialization of the object
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.obj"));
out.writeObject(student);
out.close();
//Deserialization of the object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.obj"));
Student newStudent = (Student) in.readObject();
in.close();
}
}
Running the Code
To run the code, execute the following command in the terminal:
javac Main.java && java Main