What is object serialization?
In simple terms, object serialization is a way of providing a program to read or write anobject. It allows Java objects and primitives to be encoded into a byte stream (a file) suitable for streaming. Examples of this could be within a network or even a file-system
Why do we use object serialization?
The Java platform allows us to create reusable objects in memory. However, all of those objects exist only as long as the Java virtual machine remains running. It would be nice if the objects we create could exist beyond the lifetime of the virtual machine, wouldn't it? Well, with object serialization, you can flatten your objects and reuse them in powerful ways.
With object serialization, an object's state is saved into a file as a sequence of bytes. Once an object is saved into a file you would need to retrieve it when needed right? This is a simple reverse process of converting those bytes into a live object.
An example using object serialization
Lets say we have a class called Mixture, it includes an arraylist of integers and strings.
Right, now we have this great class called Mixture that contains important word(s) and number(s) in an arraylist, but imagine if we wanted to store this in a database?
This is were object serialization comes into place
.
For us to save a Mixture object in a file, we will need to use the Serializable Class or simpler the IO Class.
Apart from importing a new class and throwing an exception, you can notice that just a slight amount of code has been added to the Mixture2 class.
Once compiling Mixture2, there should be a file created within the same directory as Mixture2. This file should be called by default mapFile or what you changed it too.
This file will then give us a strange looking amount of binary codes. This is just a binary representation of the object we saved.
This data could then be stored into a database or a server but what would we do if we wanted to retrieve the object and use it as part of our code?
This example below shows you exactly how to do that.
which is the elements we previously stored in the Mixture class.
Last but not least, remember only use Object Serialization when it is needed.
Add Comment