Java Serialization Example
Java's serialization algorithm. The algorithm to serialize an object is described as below: 1. It writes out the metadata of the class associated with an instance. It recursively writes out the description of the superclass until it finds java.lang.object. Object serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. The Java Serialization API provides a standard mechanism for developers to handle object serialization.
Learn more about custom Java serialization using the Externalizable interface.
- Java Serialization Example Last Updated on May 25th, 2017 by App Shah 6 comments Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.
- The Serialization example includes three programs. Student.java: This class is serialized. StudentWrite.java: This program creates some Student objects with some properties and writes to a file. StudentRead.java: This program reads the Student objects from the file and print their properties.
- De-Serialization: It is a process of reading the Object and it’s properties from a file along with the Object’s content. Example: Serialization of HashMap: In the below class we are storing the HashMap content in a hashmap.ser serialized file. Once you run the below code it would produce a hashmap.ser file.
Join the DZone community and get the full member experience.
What Is Java Serialization
Join For FreeIn a previous article, Everything You Need to Know About Java Serialization Explained, I explained how we can serialize/deserialize one object using the Serializable
interface and explain how we can customize the serialization process using writeObject and readObject methods.
Disadvantages of Java Serialization Process
But these customizations are not sufficient because the JVM has full control of the serialization process and those customization logics are just additions to the default serialization process. We still have to use the default serialization logic by calling ObjectOutputStream.defaultWriteObject()
and ObjectInputStream.defaultReadObject()
from writeObject
and readObject
methods. And if we do not call these default methods, our object will not be serialized/deserialized.
The default serialization process is fully recursive. So whenever we try to serialize one object, the serialization process tries to serialize all the fields (primitive and reference) with our class (except static
and transient
fields), which makes serialization a very slow process.
Now, let's assume we have an object with lots of fields that we do not want to serialize for some reason (these fields will always be assigned with default values). With the default serialization process, we will have to make all these fields transient but it still will not be efficient because there will a lot of checks to see if the fields are transient or not.
Java Serialization Vulnerability Example
So as we can see, there are lots of downsides to using the default serialization process, like:
- Customizations to serialization are not sufficient because JVM has full control of the serialization process and our customization logics are just additions to the default serialization process.
- Default serialization process is fully recursive and slow.
- In order to not to serialize a field, we have to declare it transient and lots of transient fields will again make the process slow.
- We can not control how our fields will be serialized and deserialized.
- Default serialization process does not invoke constructors while creating the object so it can not call the initialization logic provided by the constructor.
What Is the Externalization and Externalizable Interface?
As we saw above, the default Java serialization is not efficient. We can solve some of these issues by using Externalizable
interface instead of Serializable
interface.
We can write your own serialization logic by implementing the Externalizable interface and overriding it's methods writeExternal()
and readExternal()
. But with this approach, we will not get any kind of default serialization logic from the JVM and it is up to us to provide the complete serialization and deserialization logic.
So, it is very necessary to code and test these methods carefully because it might break the serialization process. But the externalization process is very fast in comparison to the default serialization process if implemented properly.
We will use below Employee
class object as an example for the explanation:
How Serialization Works With Externalizable Interface
As we can see above, in our example Employee
class, we can write your own serialization logic by implementing the Externalizable interface and overriding its methods writeExternal()
and readExternal()
.
The object can implement the writeExternal
method to save its contents by calling the methods of DataOutput
for its primitive values or calling the writeObject
method of ObjectOutput
for objects, strings, and arrays.
The object can implement the readExternal
method to restore its contents by calling the methods of DataInput
for primitive types and readObject
for objects, strings, and arrays. The readExternal
method must read the values in the same sequence and with the same types as were written by writeExternal
.
To serialize and deserialize our object to a file, we need to follow the same procedure as we followed in the Serializable example, which means calling ObjectOutputStream.writeObject()
and ObjectInputStream.readObject()
as done in the following code:
The Externalizable
interface is a child interface of Serializable
i.e. Externalizable extends Serializable
. So if we implement Externalizable
interface and override its writeExternal()
and readExternal()
methods, then our first preference is given to these methods over the default serialization mechanism provided by the JVM. These methods supersede customized implementations of writeObject
and readObject
methods. So if we also provide writeObject()
and readObject()
, then they will be ignored. Photoshop cs 7 free download.
Dec 12, 2014 Adobe Reader (formerly called Acrobat Reader) is available as a no-charge download from Adobe's web site, and allows the viewing and printing of PDF files. Acrobat and Reader are a major components of the Adobe Engagement Platform, and are widely used as a way to present information with a fixed layout similar to a paper publication. Adobe Acrobat Reader DC software is the free global standard for reliably viewing, printing, and commenting on PDF documents. And now, it's connected to the Adobe Document Cloud − making it easier than ever to work across computers and mobile devices. Adobe reader for windows xp free download - Adobe Reader for Windows 8, PDF Reader for Windows 7, PDF Reader for Windows 10, and many more programs.
In the serialization process, each object to be serialized is tested for the Externalizable
interface. If the object supports Externalizable
, the writeExternal
method is called. If the object does not support Externalizable
and does implement Serializable
, the object is saved using ObjectOutputStream
.
When an Externalizable
object is reconstructed, an instance is created using the public no-arg constructor; then the readExternal
method is called. Serializable
objects are restored by reading them from an ObjectInputStream
.
- When an
Externizable
object is reconstructed, an object is created using public no-arg constructor before thereadExternal
method is called. If a public no-arg constructor is not present, then aInvalidClassException
is thrown at runtime. - Using
Externalizable
, we can even serialize/deserialize transient variables, so declaring fields transient becomes unnecessary. - Using
Externalizable
, we can even serialize/deserialize static variables if we need to.
An Externalizable
instance can designate a substitution object via the writeReplace
and readResolve
methods documented in the Serializable
interface.
Java serialization can also be used to deep clone an object. Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of an object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a three-article long Java Cloning Series, which includes articles like Java Cloning and Types of Cloning (Shallow and Deep) in Details With Example, Java Cloning — Copy Constructor Versus Cloning, and Java Cloning — Even Copy Constructors Are Not Sufficient — go ahead and read them if you want to know more about cloning.
Differences Between Externalizable Vs. Serializable
Let's list down the main differences between Externalizable
and Serializable
interfaces in Java.
You can find the complete source code for this article on this GitHub repository. Please feel free to provide your valuable feedback in the comments below.
Like This Article? Read More From DZone
Published at DZone with permission of Naresh Joshi , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.