What is meant by "object serialization"? Can you please explain it with some examples?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Java Object Serialization
Serialization
is a mechanism to transform a graph of Java objects into an array of bytes for storage(to disk file
) or transmission(across a network
), then by using deserialization we can restore the graph of objects. Graphs of objects are restored correctly using a reference sharing mechanism. But before storing, check whether serialVersionUID from input-file/network and .class file serialVersionUID are the same. If not, throw ajava.io.InvalidClassException
.serialVersionUID is essential to the serialization process. But it is optional for the developer to add it into the java source file. If a serialVersionUID is not included, the serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.
Note - It is strongly recommended that all serializable classes explicitly declare a serialVersionUID,
since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations
, and can thus result in unexpected serialVersionUID conflicts during deserialization, causing deserialization to fail.Inspecting Serializable Classes
A class must implement java.io.Serializable interface in order to serialize its object successfully. Serializable is a marker interface and used to inform the compiler that the class implementing it has to be added serializable behavior. Here Java Virtual Machine (JVM) is responsible for its automatic serialization.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Only objects that support the java.io.Serializable or java.io.Externalizable interface can be
written to
/read from
streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.Serializable Example For Files
Serializable Example Over Network
Distributing object's state across different address spaces, either in different processes on the same computer, or even in multiple computers connected via a network, but which work together by sharing data and invoking methods.
@see
You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).
It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.
In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.
You can also prevent some data in your object from being serialized by marking the attribute as transient.
Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.
It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
Here is a very basic sample with comments to facilitate its reading:
When we run this program, the file "o.ser" is created and we can see what happened behind.
If we change the value of: someInteger to, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.
Here's a screenshot showing precisely that difference:
Can you spot the differences? ;)
There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.
Daring to answer 6 year old question, adding just a very high level understanding for people new to Java
Converting an object to bytes and bytes back to object (Deserialization).
When we want to Persist the Object. When we want the object to exist beyond the lifetime of the JVM.
ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawl details will be serialized and sent to server where the details are deserialized and used to perform operations.
Implement
java.io.Serializable
interface (marker interface so no method to implement).Persist the object: Use
java.io.ObjectOutputStream
class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).writeObject(<<instance>>)
- to write an objectreadObject()
- to read an serialized ObjectWhen you serialize an object, only the object's state will be saved, not the object's class file or methods.
When you serialized a 2 byte object, you see 51 bytes serialized file.
Answer for: How did it convert to 51 bytes file?
java.lang.Object
.Edit : One more good link to read.
This will answer a few frequent questions:
How not to serialize any field in class.
Ans: use transient keyword
When child class is serialized does parent class get serialized?
Ans: No, If parent is not extending Serializable interface parents field don't get serialized.
When parent is serialized does child class get serialized?
Ans: Yes, by default child class also get serialized.
How to avoid child class from getting serialized?
Ans: a. Override writeObject and readObject method and throw
NotSerializableException
.b. also you can mark all fields transient in child class.
My Two cents from my own blog:
Here is a detailed explanation of the Serialization: (my own blog)
Serialization:
Serialization is the process of persisting the state of an object. It is represented and stored in the form of a sequence of bytes. This can be stored in a file. The process to read the state of the object from the file and restoring it is called deserialization.
What is the need of Serialization?
In modern day architecture, there is always a need to store object state and then retrieve it. For example in Hibernate, to store a object we should make the class Serializable. What it does, is that once the object state is saved in the form of bytes it can be transferred to another system which can then read from the state and retrieve the class. The object state can come from a database or a different jvm or from a separate component. With the help of Serialization we can retrieve the Object state.
Code Example and explanation:
First let's have a look at the Item Class:
In the above code it can be seen that Item class implements Serializable.
This is the interface that enables a class to be serializable.
Now we can see a variable called serialVersionUID is initialized to Long variable. This number is calculated by the compiler based on the state of the class and the class attributes. This is the number that will help the jvm identify the state of an object when it reads the state of the object from file.
For that we can have a look at the official Oracle Documentation:
If you have noticed there is another keyword we have used which is transient.
If a field is not serializable, it must be marked transient. Here we marked the itemCostPrice as transient and don't want it to be written in a file
Now let's have a look on how to write the state of an object in the file and then read it from there.
In the above we can see an example of serialization and deserialization of an object.
For that we used two classes. For serializing the object we have used ObjectOutputStream. We have used the method writeObject to write the object in the file.
For Deserializing we have used ObjectInputStream which reads from the object from the file. It uses readObject to read the object data from the file.
The output of the above code would be like:
Notice that itemCostPrice from deserialized object is null as it was not written.
We have already discussed the basics of Java Serialization in part I of this article.
Now let's discuss it deeply and how it works.
First let's start with the serialversionuid.
The serialVersionUID is used as a version control in a Serializable class.
If you do not explicitly declare a serialVersionUID, JVM will do it for you automatically, based on various properties of the Serializable class.
Java's Algorithm of Calculating serialversionuid (Read more details here)
Java's serialization algorithm
Things To Keep In Mind:
Static fields in a class cannot be serialized.
If the serialversionuid is different in the read class it will throw a
InvalidClassException
exception.If a class implements serializable then all its sub classes will also be serializable.
If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.
Eg:
Serialization means persisting objects in java. If you want to save the state of the object and want to rebuild the state later (may be in another JVM) serialization can be used.
Note that the properties of an object is only going to be saved. If you want to resurrect the object again you should have the class file, because the member variables only will be stored and not the member functions.
eg:
The Searializable is a marker interface which marks that your class is serializable. Marker interface means that it is just an empty interface and using that interface will notify the JVM that this class can be made serializable.
Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.