Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
20.7. Custom Serialization with Externalizable
Learn content
Interactive Audio Lesson
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Today, we’ll talk about custom serialization using the Externalizable interface in Java. Can anyone tell me what serialization means?
Serialization is converting an object into a byte stream.
Exactly! Now, Externalizable is a special interface that gives us more control. Can anyone guess what that means?
Does it mean we can decide what gets serialized?
Correct! Unlike Serializable, where the JVM does it automatically, with Externalizable, we write the methods to dictate how we serialize and deserialize. Remember, we use writeExternal for serialization and readExternal for deserialization.
So we can skip serializing fields if we want?
That’s right! By controlling what's written, you can optimize performance. Let’s look at an example of the Employee class that implements Externalizable.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Now, to implement Externalizable, we need to define two crucial methods. Who can name them?
writeExternal and readExternal!
Exactly! In writeExternal, we write fields to the output stream. What do you think we must remember when doing this?
We have to make sure we write them in the correct order!
Very good! The order of serialization matters when we deserialize later. In readExternal, we’ll read those fields back. Let’s write a simple Employee class together!
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
When would you choose to use Externalizable over Serializable? Any thoughts?
Maybe when we want to control memory usage or avoid serializing certain fields?
Exactly! With Externalizable, we can enhance performance by serializing only what we need. Can anyone describe a scenario where this might be beneficial?
Like if we have sensitive information, we could skip it?
Perfect! Sensitive information can be excluded from serialization. That’s why customizing the serialization process is so valuable!
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
To wrap things up, what are some best practices you should keep in mind when using Externalizable?
Always define a default constructor!
And ensure proper handling of exceptions during serialization and deserialization!
Great points! Remember, without a default constructor, deserialization will fail. Exception handling is also critical to prevent errors. Any final questions?
So, if I remember correctly, Externalizable gives us more control but requires more work?
Spot on! It’s a trade-off between control and convenience. Excellent discussion today!
Overview
Short Summary
This section introduces the Externalizable interface in Java, which provides a way to control the serialization process of custom objects.
Medium Summary
In this section, we explore the Externalizable interface, which extends Serializable. It allows developers to implement custom serialization logic by defining the writeExternal and readExternal methods. This is useful for optimizing serialization processes and managing how class fields are serialized and deserialized.
Detailed Summary
Custom Serialization with Externalizable
The Externalizable interface in Java enables a more flexible approach to serialization compared to the default mechanism provided by the Serializable interface. Unlike Serializable, which handles serialization automatically, Externalizable requires the programmer to define their own methods for writing and reading the object's state.
-
Definition: The Externalizable interface extends Serializable and mandates the implementation of two methods:
writeExternal(ObjectOutput out): This method is called during serialization. The developer must implement the logic to convert the object’s state into a byte stream, using the provided ObjectOutput instance.readExternal(ObjectInput in): This method is called during deserialization, where the developer specifies how to restore the object’s state from the byte stream.
-
Use Case: One of the significant advantages of using Externalizable is the ability to optimize serialization by selectively writing and reading fields, which can improve performance and reduce memory usage. This is especially beneficial when dealing with large objects or collections.
-
Example Implementation: The section provides an example of a class
Employeethat implements Externalizable to control its serialization and deserialization process, explaining how each method is leveraged to save and restore object data efficiently.
Understanding and using Externalizable is crucial for developers who want to have precise control over their objects' serialization processes.
Reference YouTube Videos
Audio Book
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountThe Externalizable interface allows control over serialization logic.
public interface Externalizable extends Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}Detailed Explanation
The Externalizable interface is a specialized way of handling serialization in Java. Unlike the Serializable interface, which uses default serialization, Externalizable gives you full control over how your object is serialized and deserialized. When you implement this interface, you need to explicitly define two methods: writeExternal and readExternal. The writeExternal method is responsible for defining how the object is converted into a byte stream, while the readExternal method defines how to reconstruct the object from that byte stream.
Examples & Analogies
Think of Externalizable as a recipe for baking a cake, where you have complete control over every ingredient and the baking process. Just like a baker can choose whether to add frosting or nuts based on their preferences, a developer can choose which attributes of a class to serialize and how to do it using the Externalizable interface.
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountExample
class Employee implements Externalizable {
int id;
String name;
public Employee() {}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(id);
out.writeObject(name);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
id = in.readInt();
name = (String) in.readObject();
}
}Detailed Explanation
In this example, we have a class Employee that implements the Externalizable interface. The class has two attributes: id (an integer) and name (a string). The parameterless constructor is essential for deserialization because it allows the creation of an object without any initial attribute values. The writeExternal method specifies that during serialization, the id and name should be written to the output stream. Conversely, the readExternal method retrieves those values from the input stream and assigns them back to the object's attributes during deserialization.
Examples & Analogies
Consider the Employee class like an application form. When you apply for a job (serialization), you fill out your ID and name on the form. When the employer wants to review your details (deserialization), they read your form to get your ID and name back. This process requires both the form and a way to read and interpret it.
--
Key concepts
Core takeaways and short definitions to help you quickly recall the key ideas from this section.
- Externalizable Interface:
Allows control over the serialization process by defining custom methods.
- writeExternal:
Method to serialize the object's state.
- readExternal:
Method to deserialize the object's state.
Examples
Memory aids
Imagine you own a magical book that only reveals its secrets when asked correctly. The Externalizable interface is like that book, granting you permission to choose which secrets (fields) to share when telling your story (serialization).
Remember the acronym 'WE' for Externalization: 'W' means writeExternal and 'E' stands for readExternal.
Flash Cards
Glossary
Externalizable
An interface in Java that allows custom serialization of objects by implementing methods to define how an object's state is serialized and deserialized.
writeExternal
A method defined in the Externalizable interface for writing an object's state to an output stream.
readExternal
A method defined in the Externalizable interface for reading an object's state from an input stream.