→ Conversation of object’s state into byte stream.
→ Useful when you need to save an object’s state to a file, send it over network, or store it in a database.
Serialization in Java refers to the process of converting an object's state into a byte stream, which can be easily stored, transmitted, or reconstructed. This is particularly useful when you need to save an object's state to a file, send it over a network, or store it in a database. Java provides a built-in mechanism for serialization using the java.io.Serializable interface and the ObjectOutputStream and ObjectInputStream classes.
Here's a basic overview of how serialization works in Java:
java.io.Serializable interface:
To make an object serializable, you need to implement the Serializable interface. This is a marker interface, which means it doesn't have any methods that you need to implement. It simply indicates that the class can be serialized.javaCopy code
import java.io.Serializable;
public class MyClass implements Serializable {
// Class members, constructor, methods, etc.
}
ObjectOutputStream to write the object's state to a stream, typically a file output stream.javaCopy code
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerializationDemo {
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);
System.out.println("Object serialized and saved to myObject.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectInputStream to read the serialized byte stream and reconstruct the original object.javaCopy code
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class DeserializationDemo {
public static void main(String[] args) {
try (FileInputStream fileIn = new FileInputStream("myObject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
MyClass myObject = (MyClass) in.readObject();
System.out.println("Object deserialized from myObject.ser");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
It's important to note that not all objects can be serialized. For example, objects that contain references to non-serializable objects or objects marked as transient won't be serialized by default. You'll need to handle such cases in your code.
Also, be aware of potential security concerns with deserialization, as it can execute arbitrary code during the deserialization process. It's recommended to use serialization carefully and only with trusted data sources.