Talking about Serialization in Java

Serialization is a concept that allows us to convert the state of a Java object into a certain format so that this Java object can be stored somewhere and then it will be used by another process.

Normally, when using Serialization, our Java object will be converted to byte streams and we can store this byte stream in memory, on disk, transmitted over the network to a certain server or can also save them in the database.

And when another process uses a serialized Java object, it converts the Serialization format to the state of the original Java object. Thanks to that, the process can reuse our Java object.

In order for an object to be able to use serialization, we must let our object implement an interface called This interface does not have any methods to implement.

To understand better, I will create an example to prove what I just said!

For example, I have an object Student:

Because I want to use Serialization, I will implement the Serializable interface for the Student object as follow:

As you can see, I added a variable named serialVersionUID into my Student object. The purpose of this variable is to make sure before and after the conversion, our Student class is the same.

OK, now we are going to write code to convert the Student object and save its byte streams to a certain file!

Now, a file has been created and if you examine the file that you saved your Student object, you will see something like this:

So how can other process use the file we created in the example above, we write the next code:

Kết quả:

As you saw before and after the conversion, your Student object still has the information that we saved earlier.

Chia sẽ bài viết này ...Share on Facebook
0Tweet about this on Twitter
Share on LinkedIn

Add Comment