Java Serialization
Serialization in Java is the process of converting an object's state into a byte stream so that it can be saved to a file or transmitted over a network. Deserialization is the reverse process of reconstructing the object from the byte stream.
1. Implementing Serializable
To make a class serializable, it must implement the Serializable
interface, which is a marker interface with no methods.
Example:
Person.java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// Constructors, getters, and setters
}
2. Serializing Objects
Use ObjectOutputStream
along with FileOutputStream
to serialize an object to a file.
Example:
SerializeExample.java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerializeExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try {
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
fos.close();
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Deserializing Objects
Use ObjectInputStream
along with FileInputStream
to deserialize an object from a file.
Example:
DeserializeExample.java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class DeserializeExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Person person = (Person) ois.readObject();
ois.close();
fis.close();
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
4. The transient
Keyword
Fields marked with transient
are not serialized. Use this keyword for sensitive information or data that can be recalculated.
Example:
Person.java
public class Person implements Serializable {
private String name;
private transient int age; // Will not be serialized
}
5. The serialVersionUID
It's good practice to declare a serialVersionUID
field in serializable classes to ensure version compatibility.
private static final long serialVersionUID = 1L;
6. Key Takeaways
- Serialization allows saving and restoring object states.
- Implement
Serializable
to enable serialization. - Use
transient
to exclude fields from serialization. - Declare
serialVersionUID
for version control. - Be cautious with serialization and security; sensitive data should be handled appropriately.