How to serialize object java
How to serialize object java
Serializable Objects
To serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object. A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. Deserialization is the process of converting the serialized form of an object back into a copy of the object.
For example, the java.awt.Button class implements the Serializable interface, so you can serialize a java.awt.Button object and store that serialized state in a file. Later, you can read back the serialized state and deserialize into a java.awt.Button object.
The Java platform specifies a default way by which serializable objects are serialized. A (Java) class can override this default serialization and define its own way of serializing objects of that class. The Object Serialization Specification describes object serialization in detail.
When an object is serialized, information that identifies its class is recorded in the serialized stream. However, the class’s definition («class file») itself is not recorded. It is the responsibility of the system that is deserializing the object to determine how to locate and load the necessary class files. For example, a Java application might include in its classpath a JAR file that contains the class files of the serialized object(s) or load the class definitions by using information stored in the directory, as explained later in this lesson.
Binding a Serializable Object
You can store a serializable object in the directory if the underlying service provider supports that action, as does Oracle’s LDAP service provider.
Running this example produces the following output.
Specifying a Codebase
Note: The procedures described here are for binding a serializable object in a directory service that follows the schema defined in RFC 2713. These procedures might not be generally applicable to other naming and directory services that support binding a serializable object with a specified codebase.
When a serialized object is bound in the directory as shown in the previous example, applications that read the serialized object from the directory must have access to the class definitions necessary to deserialize the object.
Serialization and Deserialization in Java with Example
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
The ObjectInputStream class contains readObject() method for deserializing an object.
Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
Only the objects of those classes can be serialized which are implementing java.io.Serializable interface.
Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote.
Points to remember
1. If a parent class has implemented Serializable interface then child class doesn’t need to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via Serialization process.So, if you don’t want to save value of a non-static data member then make it transient.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.
Example :
SerialVersionUID
The Serialization runtime associates a version number with each Serializable class called a SerialVersionUID, which is used during Deserialization to verify that sender and receiver of a serialized object have loaded classes for that object which are compatible with respect to serialization. If the receiver has loaded a class for the object that has different UID than that of corresponding sender’s class, the Deserialization will result in an InvalidClassException. A Serializable class can declare its own UID explicitly by declaring a field name.
It must be static, final and of type long.
i.e- ANY-ACCESS-MODIFIER static final long serialVersionUID=42L;
If a serializable class doesn’t explicitly declare a serialVersionUID, then the serialization runtime will calculate a default one for that class based on various aspects of class, as described in Java Object Serialization Specification. However it is strongly recommended that all serializable classes explicitly declare serialVersionUID value, since its computation is highly sensitive to class details that may vary depending on compiler implementations, any change in class or using different id may affect the serialized data.
It is also recommended to use private modifier for UID since it is not useful as inherited member.
serialver
The serialver is a tool that comes with JDK. It is used to get serialVersionUID number for Java classes.
You can run the following command to get serialVersionUID
serialver [-classpath classpath] [-show] [classname…]
How to serialize an object into a string
I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should use BLOB. It is pretty straighforward with JDBC.
The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.
If you still want to write it down into a String you can encode the bytes using java.util.Base64.
Still you should use CLOB as data type because you don’t know how long the serialized data is going to be.
Here is a sample of how to use it.
NOTE: for Java 7 and earlier you can see the original answer here
How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream?
Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.
Thanks for great and quick replies. I will gives some up votes inmediately to acknowledge your help. I have coded the best solution in my opinion based on your answers.
Note i did not considered using JSON because is less efficient.
Note: I will considered your advice about not storing serialized object as strings in the database but byte[] instead.
Java8 approach, converting Object from/to String, inspired by answer from OscarRyz. For de-/encoding, java.util.Base64 is required and used.
XStream provides a simple utility for serializing/deserializing to/from XML, and it’s very quick. Storing XML CLOBs rather than binary BLOBS is going to be less fragile, not to mention more readable.
How about persisting the object as a blob
If you’re storing an object as binary data in the database, then you really should use a BLOB datatype. The database is able to store it more efficiently, and you don’t have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.
If you absolutely need to store the data as a String, I would recommend XStream for XML-based storage (much easier than XMLEncoder ), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.
Take a look at the java.sql.PreparedStatement class, specifically the function
Then take a look at the java.sql.ResultSet class, specifically the function
Keep in mind that if you are serializing an object into a database, and then you change the object in your code in a new version, the deserialization process can easily fail because your object’s signature changed. I once made this mistake with storing a custom Preferences serialized and then making a change to the Preferences definition. Suddenly I couldn’t read any of the previously serialized information.
Java Serialization
Recently, after a long time, I had the opportunity to look more in the java serialization mechanism. As a developer, mostly we are using java serialization based on the requirements. Here are some must-know facts of the Java Serialization mechanism.
Note: All the code samples are uploaded to GitHub and you can find it here.
DIL8654/JavaSerialization
Contribute to DIL8654/JavaSerialization development by creating an account on GitHub.
What are Serialization and Deserialization?
Serialization in Java allows the developer to convert a java object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting object stream which is serialized to actual Java object to be used in our program.
Serialization in Java is very easy to use initially but it comes with some important security and integrity problems if serialization not happened correctly.
Note: Serialization in Java was introduced in JDK 1.1
How to Serialize Java Object
If we want to serialize a Java object, we will have to implement the below java interface which is a marker interface that has no methods or fields to implement by the implemented object. That means marker interfaces are just telling to the JVM that this object has something to do in JVM scope.
If you want to make some of the fields in your java bean not to serialize, you can do it by making them transient.
We need some helper utility class to define if we want to serialize (write) our objects to file and de-serialize (read) from the file. So below is the utility class:
So now we can write some test class to serialize the object and deserialize the object as below:
you can see the output like this:
See the difference between the above outputs. we have marked age fields as transient so that the field is not written into the file, that is why it was initialized as 0 in deserialized output.
The ser file extension is associated with Java.
The ser files contain serialized object data. Java object serialization is Java’s built-in mechanism for manipulating objects as streams of bytes.
Object serialization provides the foundation for Java’s remote method invocation (RMI) capabilities that enable Java programs that are distributed over a network to invoke each other so-called “remote methods.” RMI is used frequently in distributed enterprise applications that are built with Java Enterprise Edition (Java EE).
How is the impact if class fields are refactored
So what happened the object has changed once the same object is already serialized into a file or saved into a database.
Java allows some changes to be done to the object if only those changes are ignorable.
Because above all options are just like as adding a new field to the object. because transient fields and static fields are non-serializable. So removing classifier means like an adding new field to the object. Let’s try that with a code sample.
In above example, we have already serialized Student object to a file. Let’s try adding a new field to the same object with getters and setters.
Let’s have a test class to test the scenario:
Let’s see the output, Oops! it is an error. So adding a new field is not ignoring and it is a violation of the above points then.
Let’s investigate more about this. The error is saying that there is an incompatibility of objects and some information about serialVersionUID. The reason is:
The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
Let’s try with adding serialVersionUID to the object and see the output.
Now we get the correct output.
What if Developer needed some integrity check for the serialized object
Means that, if the developer wants to modify the object to make some changes of the field values before serialization and verify them in the deserialization process. This is must when you make your object securable and if the object has tampered when it is stored the disk or traveling over the network.
Java has provided some another interface to achieve that objective which is:
developer must provide implementation of writeExternal() and readExternal() methods to be used in serialization process.
Here is the example of the serializable object which implemented above-mentioned methods to achieve the objective.
According to the above code, we can check/verify the data and handle errors accordingly.
Serialization with Inheritance
As developers, When we are developing the java applications we are using basic OOP concepts and the most widely used concept is inheritance.
So that we need to extend a class that doesn’t implement the Serializable interface. If we using are based on the automatic behavior then it will not function as expected.
This is one place, where readObject() and writeObject() methods really help. By providing their implementation, we can save the superclass state to the stream and then retrieve it later on. Let’s see this in action.
Note: But around, If the superclass is implemented by the Serialization interface, all the subclasses of the hierarchy will be eligible for serialization.
Some Methods related to Serialization
These methods are used for serialization purposes.
Usually while implementing the above methods, the best practice is to keep as private so that subclasses can’t override them. They are meant for serialization purpose only and keeping them private avoids any security issue.
Hope that you have had some understanding about the Java Serialization and Deserialization of the Objects.
Serialization is one of the important but confusing concepts in Java. Even experienced Java developers struggle to implement Serialization correctly. The Serialisation mechanism is provided by Java to save and restore the state of an object programmatically. Java provides two classes Serializable and Externalizable in java.io package to facilitate this process, both are marker interfaces i.e. an interface without any methods. Serializing an Object in Java means converting it into a wire format so that you can either persist its state in a file locally or transfer it to another client via the network, hence it becomes an extremely important concept in distributed applications running across several JVMs.
There are other features in Java like Remote Method Invocation (RMI) or HttpSession in Servlet API which mandates the participating object should implement a Serializable interface because they may be transferred and saved across the network.
You can also read Head First Java to learn more about the subtle details of Serialization in Java. They have covered the serialization topic just right, with neither too much detail nor trivial explanation. I have learned a lot of useful details from there.
I have also explained the reverse process of Serialization to restore the state of the object i.e. de-serialization and why SerialVersionUID is important for any serializable class. Once we restore the object we print its state to compare values before serialization. This will give you a clear idea of how you can save and restore objects in Java.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
Java Program to Serialize an Object using Serializable interface
The second class is our application class which contains the main() method, all the code to create an object, saving it, and finally restoring it written inside the main method.
A picture is worth a thousand words, so here is a diagram that explains the serialization and deserialization process from a 10K feet view:
Observation and Explanation
The SerialVersionUID is a very important field for a serializable class and you should always define it. If you don’t define then JVM will calculate this value by reading the structure of the class e.g. number of instance variables, their types, etc.
This means next time you add another instance variable or you remove the old one, you risk getting a different SerialVersionUID and if that happens you won’t be able to restore the object saved by the previous version of your program.
This has actually happened to us when one of the developers accidentally removed the SerialVersionUID from one of the user preferences classes and when the user downloads and run the new version of our Java application, his preferences were all gone.
He was a trader and for them, their preferences mean a lot, it was a hard time to console and pacify him before we reverted back his GUI to the previous version and restored his preferences. I am sure, you would never want to upset your clients and user.
Serialization is full of such details and I highly recommend reading Joshua Bloch’s advice on Effective Java related to Serialization before implementing it in your real-world project. Those are invaluable pieces of advice and key to successfully and correctly implement Serliazable in anything other than a demo program like this one.
Now let’s come to a simple, non-final static variable, its value is also not persisted during Serialization, that’s why you see _brand=Nike before Serialization and _brand=Adidas after.
Do you know why it happened? because when we created another instance of Shoe for Adidas, we reset the value of this variable to «Adidas», and since the constructor is not called during deserialization, and the class is not loaded again, its value remains «Adidas». It could have been null if de-serialization would have taken place at another JVM instance.
Now just initialize that variable as Thread _thread = new Thread() and re-run the program again. This time will get the following Exception :
That’s why I recommend putting a Serialization alert in the source file of a Serializable class, reminding them about not adding any variable which is not serializable or making it transient if they really need it. You can further see Java Coding Guidelines for more coding best practices while writing Java applications. It contains 75 recommendations for reliable and secure Java programs.
For example, transient and static variables are not saved during serialization, if you declare a static variable, make sure it’s not final, and remember that constructor is not called during the de-serialization process.
All these concepts are very important to implement serialization correctly in your program. You can further read Effective Java by Joshua Bloch to understand effective serialization e.g. with custom binary formats. All the items related to Serialization in this book are a must-read for any serious Java developer.