How to Deserialize Object in Java: Simple Guide with Example
To deserialize an object in Java, use
ObjectInputStream to read the object from a file or stream and cast it back to its original class. This process reverses serialization, restoring the object's state from bytes.Syntax
Deserialization in Java uses ObjectInputStream to read bytes and convert them back into an object. The main steps are:
- Create an
ObjectInputStreamfrom anInputStream(like aFileInputStream). - Call
readObject()to get the object. - Cast the returned
Objectto the original class.
java
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.ser")); MyClass obj = (MyClass) ois.readObject(); ois.close();
Example
This example shows how to deserialize a Person object from a file named person.ser. The Person class implements Serializable to allow serialization and deserialization.
java
import java.io.*; class Person implements Serializable { private static final long serialVersionUID = 1L; String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class DeserializeExample { public static void main(String[] args) { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) { Person p = (Person) ois.readObject(); System.out.println("Deserialized: " + p); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
Output
Deserialized: Person{name='Alice', age=30}
Common Pitfalls
- ClassNotFoundException: Happens if the class of the serialized object is not found in the classpath during deserialization.
- serialVersionUID mismatch: If the class has changed and the
serialVersionUIDdoes not match, deserialization fails. - Not implementing Serializable: The class must implement
Serializableor deserialization will throwNotSerializableException. - File not found or corrupted data: The file must exist and contain valid serialized data.
Wrong way: Trying to deserialize without casting or from a wrong file.
Right way: Always cast the object and handle exceptions properly.
java
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("wrongfile.ser"))) { // Wrong: no cast Object obj = ois.readObject(); // Right: cast to expected class Person p = (Person) obj; } catch (Exception e) { e.printStackTrace(); }
Quick Reference
Remember these key points for deserialization:
- Use
ObjectInputStreamwrapped around anInputStream. - Call
readObject()and cast the result. - Handle
IOExceptionandClassNotFoundException. - Ensure the class implements
Serializableand has a matchingserialVersionUID.
Key Takeaways
Use ObjectInputStream and readObject() to deserialize objects in Java.
Always cast the deserialized object to its original class.
Handle IOException and ClassNotFoundException during deserialization.
Ensure the class implements Serializable and has a consistent serialVersionUID.
Deserialization restores the object's state from bytes saved during serialization.