Java provides a mechanism called serialization. The Java object is persistent through orderly format or byte sequence, which contains the data of the object, as well as the type of the object, and the data type saved in the object.
Therefore, if we have serialized a object, it can be read and deactivated through the type of object and other information, and finally obtains the prototype of the object.
ObjectInputStream and ObjectOutPutStream objects are high -level streaming objects, including serialization and back -sequential methods.
ObjectoutPutStream has many methods for serialized objects. The most commonly used is:
Private Void WriteObject (ObjectoutPutstream OS) Throws IOEXCEPTION {}
Similar ObjectInputStream provides the following methods:
Private void brand (ObjectInputStream is) Throws IOEXCEPTION, ClassNotFoundexception {}
So where does it need to be serialized? Serialization usually uses network transmission data, or saves objects to files. The data mentioned here is an object and not a text.
The problem now is that our network architecture and hard disk can only identify binary and bytes, and cannot recognize Java objects.
Serialization is to translate Value/States in the Java object into bytes to transmit or save via the network. In addition, the dependency serialization is to read the byte code and translate it back to the Java object.
SerialVersionuid concept
SerialVersionuid is used to ensure the same object (which can be used in serialization) can be loaded during the deserialization process. SerialVersionuid is a version control for objects. You can refer to SerialVersionuid in Java Serialization to get more information.
For serialization:
The steps are as follows:
Let's see a list:
Create Employee.java in src-> org.arpit.javapostsforning
1.employee.java
package org.arpit.javapostsforning; Import Java.io.serializable; Public Class Employ Implements Serializable {Int Employeeid; String Ename; String department; Public int Getemployeid () {Return Employeid;} Public Void SetempLoyeeid (int Employeeid) {this.employeeid = Employeeid;} Public String Getemployeename () {Return Employeeename;} Public Void Setemployeename (String Employeename) {This.employeena Me = Employeename;} Public String GetDepPartment () {Return department;} Public void SetDepment (String department) {this.Depapartment = department;}}
As you can see, if you need to serialize any class, then you must implement the Serializable interface. This interface is a marker interface.
The marker interface in Java is an interface without any field or method. In simple terms, the empty interface is called the marker interface in Java.
2.Serializemain.java
package org.arpit.javapostsforning; Import Java.io.fileoutPutstream; Import Java.io.ioException; Import Java.io.objectPuttream; Lass Serializemain { / ** * @Author Arpit Mandliya * / Public Static Void Main (String [] [] Args) {Employee Emp = New Employee (); Emp.SetemployEID (101); Emp.SetempLoyeename ("Arpit"); Emp.SetDepapartMent ("CS"); try {fileoutput Stream fileout = new fileoutputstream ("" embroyee.ser ") ; ObjectPutstream Outstream = New ObjectPutstream (Fileout); OutStream.writeObject (EMP); Outstream.Close (); Exception I) {i.printstacktrace ();}}}
For back -sequentialization:
The step is
In the package src-> org.arpit.javapostsForlearning, create Deserializemain.java
3.Deserializemain.java
Package org.arpit.javapostsforning; Import Java.io.ioException; Import Java.io.objectInputStream; Public Class Deseerialize { /*** @Aut HOR ARPIT MANDLIYA */ PUBLIC Static Void Main (String [] ARGS) {Employee Emp = Null ; Try {FileInputStream Filein = New FileInputStream ("Employee.Ser"); ObjectInputStream in = New ObjectInputStream (Filein); Emp = (Employee) t (); in.close (); filein.close ();} Catch (IOEXCEPTION I) {I.printstacktrace (); Return;} Catch (ClassNotFoundexception C) {System.out.println ("Employeeeeee Found"); C.PRINTSTST acsttrace (); Return;} System.out.println (" DESERIALIZED EMPLOYEE ... "); System.out.println (" Emp ID: " + Emp.Getemployeeid ()); System.out.println (" name: " + Emp.GetempLoyeename ()); STEM.out.println ("Department:" + Emp.getDepPartment ());}}
4. Run:
First run the Serializemain.java, and then run the deserializemain.java, you will get the following results:
Deserialized emblayee ... Emp ID: 101Name: ArpitDepapartment: CS
In this way, we serialized an EMPLOYEE object and carried out it to it. This looks simple, but if it contains object references and inheritance, the situation will become complicated. Let's take a look at the examples one by one to see how to achieve serialization on various occasions.
Case 1 -If the object quotes other objects, what should I do
We have already seen the simplest sequence -based examples. Now we see how to deal with other objects in the object. How can we serialize? Will the cited object also serialize? Yes, you do not need to be explicitly serialized. When you serialize any object, if it contains reference objects, then Java serialization will automatically serialize the entire object diagram of the object. For example, Employee now quotes an address object, and address also quotes other objects (for example, home), then when you serialize the Employee object, all other cited objects, such as address and Home, will be automatically serialized by serialization. Essence Let's create the address class and add the object of the address as a reference to add it to the Employee class.
Employee.java:
package org.arpit.javapostsforning; Import Java.io.serializable; Public Class Employ Implements Serializable {Int Employeeid; String Ename; String department; address address; public int Getemployeid () {Return Emplayeeid;} Public void setemplayeid (int Emplayeeid) { This.employeeid = Employeeid;} Public String GeTemPloyeename () {Return Employeeeename;} Public Void Setempoloyeename (String Employeename) {This.emplayeename = Employeeename;} Public String GetDepPartment () {Return department;} Public Void SetDeppartment (String department) { This.Department = department;} Public Address GetAddress () {Return Address;} Public Void SetadDress (Address Address) {this.address = address; }}
In ORG.ARPIT.JAVAPOSTSFORLERNING package, create address.java
Address.java:
package org.arpit.javapostsforning; Public Class Address {int HomeNo; String Street; String City; Public Address (Int HomeNo, String Street, String Cit y) {super (); this.homeno = HOMENO; this.Street = Street; this .City = City;} Public Int Gethomeno () {Return Homeno;} Public Void Sethomeno (int Home) {this.homeno = HOMENO;} Public StringStStreet () { Street;} Public Void SetStreet (String Street) {this .Street = Street;} Public String GetCity () {Return City;} Public Void SetCity (String City) {this.City = City;}}
In the ORG.ARPIT.JAVAPOSTSFORLERNING, create a SerializedeSerializemain.java
Serializedeserializemain.java:
Package org.arpit.javapostsforning; Import Java.io.FileInputStream; Import Java.io.fileoutStream; Import Java.io.ioxception; Import .ObjectInputStream; Import Java.io.ObjectPutstream; Public Class SerializedESerializemain { /*** @AUTHOR Arpit Mandliya */ Public Static Void Main (String [] ARGS) {Employee Emp = New Employee (); Emp.SeTemPlayeeid (101); ("Arpit"); Emp.setDepPartment ("CS"); Address Address = New Address (88, "mg Road", "PUNE"); Emp.setAddress (Address); // Serialize Try {FileoutStream Fileout = New FileoutPutstream ("EM" ployee.ser "); );; Outstream.close (); Fileout.close ();} Catch (IOEXCEPTION I) {I.Printstacktrace ();} /deserialize emp = l; Try {FileInputStream Filein = New Fileinputstream ( "Employeee.Ser"); ObjectInputStream in = New ObjectInputStream (FileIn); Emp = (Employee) in.reamObject (); in.Close (); OException I) {i.printstacktrace ( ); Return;} Catch (ClassNotFoundexception C) {System.out.println ("Employeeeeee Found"); .println ("Deserialized Employee ..."); System .out.println ("EMP ID:" + Emp.Getemployeeid ()); System.out.println ("name:" + Emp.Getemployeename ()); mp.getDepartment ()); Address = EMP.Getaddress (); System.out.println ("CITY:"+Address.getCity ());}
Run it:
When you run SerializedEserializemain.java. You will get such a result:
java.Io.notserializableException: Org.arpit.javapostsforning.address at Java.io.objectPuttream.writeObject0 (UNKNOWN SOURCE) at Java.i O.ObjectPutstream.defaultWriteFields (Unknown Source) at java.io.objectPuttream.writeSerialData (UNKNOWN SOURCE) at java.iO.ObjectPutstream.writeordinaryObject (UNKNOWN SOURCE) at java.io.ObjectPuttream.writeObject0 (UNKNOWN SOURCE) at Java.io.ob.ob JECTOUTPUTSTREAM.WRiteObject (unknown source)
We will explain where it is wrong. I forgot to say that the address class must also be Serializable. Then the address class must inherit the Serialzable interface.
Address.java:
Import Java.io.serializable; Public Class Address Implements Serializable {int HomeNo; String City; Public Address (Int HomeNo, String t, string city) {super (); this.homeno = HomeNo; this.Street = Street This; this.City = City;} Public int Gethomeno () {Return HomeNo;} Public Void Sethomeno (int HomeNo) {this.homeno = homeno;} Public Stringstreet () {) Return Street;} Public Void SetStreet (String Street) {This.Street = Street;} Public String GetCity () {Return City;} Public Void SetCity (String City) {this.City = City;}}}
Run again:
When you run again Serializedeserializemain.java. You can get the following results
Deserialized emblayee ... Emp ID: 101Name: ArpitDepartment: CSCity: Pune
Case 2: If we cannot access the source code of the reference object (for example, you cannot access the source code of the address class above)
If we cannot access the address class, how can we implement the Serializable interface in the address class? Is there another way to achieve it? Yes, you can create another class, inherit the address, and then let it inherit the Serializable interface, but for the following situation, this solution will fail:
If the reference class is defined as the final
If the reference class references another non -serialized object
So, how can we serialize the EMPLOYEE object? The solution is to mark the transition. If you don't need to serialize any field, just mark it as Transient.
Transient address address
In the Employee class, after the adDRESS is marked as a transient, run the program. You will get nullpointerexception, because the address reference will be NULL during the process of deepery.
Case 3 -What if I still need to save the state of the reference object? (For example, address object)
If you marked the adDRESS as transient during the process of deepertine, it will return the NULL result. But if you still need to save its state, you need to serialize the address object. Java serialization provides a mechanism. If you have a specific signature Private method, then they will be called during serialization and deepertine. Employee objects are called during serialization/derivativeization.
Employee.java:
package org.arpit.javapostsforning; Import Java.io.ioException; Import Java.io.objectInputStream; Import Java.objectPuttream; Import ava.io.Serializable; Public Class Employ Implements Serializable {int Employeeid; String Employeeename; String Department; transient Address address; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = Employeename;} Public String GetDepapartment () {Return department;} Public void SetDepartment (String department) } PUBLIC Address Getaddress () {Return Address;} Public Void Setaddress (address address) {this.address = address;} Private Void WriteObject (ObjectOutPutstream OS) Throws IOEXCEPTION, ClassNotFoundexception {Try {OS.DefaultWriteObject (); O. s.writeint (address.gethomeno ()); Os.WriteObject address.getCity ());} Catch (Exception E) {e.printstacktrace ();}} PRIVATE VOID ReadObject (ObjectInputStream is) Throws IOEXCETION Foundexception {try {is.DefaultReadobject (); int HomeNo = is.Readint () ; String Street = (String) is.Readobject (); String City = (String) is.Readobject (); address = new address (HomeNo, STREET, City);} Catch (Exception E) {e.printstacktrace (); }}}
Another thing to keep in mind, ObjectInputStream reads the order of data from ObjectoutPutstream. The order of data writing data is consistent.
Create address.java
Address.java:
Package org.arpit.javapostsforning; Import Java.io.serializable; Public Class Address {int HomeNo; String String City; Public Address t Homeno, String Street, String City) {Super (); this.Homeno = HOMENO; this.Street = Street; this.City = City;} Public int GetHomeno () {Return Homeno;} Public void Sethomeno (Int HomeNo) {this.homeno = Public String getStreet () {Return Street;} Public void SetStreet (String Street) {This.Street = Street;} Public String GetCity () {Return City;} Public Void SetCity (String City) {this.City = City; }}
Create SerializeDeserializemain.java
Serializedeserializemain.java:
Package org.arpit.javapostsforning; Import Java.io.FileInputStream; Import Java.io.fileoutStream; Import Java.io.ioxception; Import .ObjectInputStream; Import Java.io.ObjectPutstream; Public Class SerializedESerializemain { /*** @AUTHOR Arpit Mandliya */ Public Static Void Main (String [] ARGS) {Employee Emp = New Employee (); Emp.SeTemPlayeeid (101); ("Arpit"); Emp.setDepPartment ("CS"); Address Address = New Address (88, "mg Road", "PUNE"); Emp.setAddress (Address); // Serialize Try {FileoutStream Fileout = New FileoutPutstream ("EM" ployee.ser "); );; Outstream.close (); Fileout.close ();} Catch (IOEXCEPTION I) {I.Printstacktrace ();} /deserialize emp = l; Try {FileInputStream Filein = New Fileinputstream ( "Employeee.Ser"); ObjectInputStream in = New ObjectInputStream (FileIn); Emp = (Employee) in.reamObject (); in.Close (); OException I) {i.printstacktrace ( ); Return;} Catch (ClassNotFoundexception C) {System.out.println ("Employeeeeee Found"); .println ("Deserialized Employee ..."); System .out.println ("EMP ID:" + Emp.Getemployeeid ()); System.out.println ("name:" + Emp.Getemployeename ()); mp.getDepartment ()); Address = EMP.Getaddress (); System.out.println ("CITY:"+Address.getCity ());}
run:
When you run SerializeDeserializemain.java. You will get the following results:
Deserialized emblayee ... Emp ID: 101Name: ArpitDepartment: CSCity: Pune
Now we get the state of the address object, just like it before it is serialized.
Inheritance in serialization:
Now let's see how the inheritance affects serialization. Regardless of whether the parent class is serialized, this will lead to many examples. If the parent class is not serialized, what will we do and how it works. Let's take a look at the example.
We will create a Person.java as the parent class of Employee.
Case 4: If the parent class is serialized
If the parent class can serialize, all inheritance classes will be serialized.
Case 5: What if the parent class is not serialized?
If the parent class is non -serialized, our processing methods will be very different.
If the parent class is non -serialized, then it must not have a parameter constructor function.
Person.java
Package org.arpit.javapostsforning; Public Class Person {String name = "Default"; String Nationality; Public Person () {System.out.println ("Person : Constructor ");} Public Person (String name, String Nationality) { Super (); this.Name = name; this.NATIONALITY = Nationality;} Public String getName () {Return name;} Public void setname (string name) {this .name = name;} Public String getnationality () {Return Nationality ;} Public Void Setnationality (String Nationality) {this.nationality = Nationality;}}
Create Employee.java
Employee.java:
Package org.arpit.javapostsforning; Import Java.io.serializable; Public Class EmployeeeeeeeeeeeeeEEEEEEEEEEEEEEEEEEILINTS Serializable {int Emplayeeid; ST Ring department; Public Employee (int Employeeid, String name, String DEPARTMENT, String Nationality) {Super (name, Nationality) ; This.employeeid = Employeeid; this.Department = department; System.out.println ("Employee: Constructor"); Return Employeid;} Public Void Setemployeeid (int Employeeid) {this.employeeid = Employeeid ;} Public String getDepapartment () {Return department;} Public void SetDepPartment (String department) {this.Deppartment = department;}}
Create SerializeDeserializemain.java
Serializedeserializemain.java:
Package org.arpit.javapostsforning; Import Java.io.FileInputStream; Import Java.io.fileoutStream; Import Java.io.ioxception; Import .ObjectInputStream; Import Java.io.ObjectPutstream; Public Class SerializedESerializemain { /*** @AUTHOR Arpit Mandliya */Public Static Void Main (String [] ARGS) {// Serialize Employeee Emp = New Employee (101, "Arpit", "Indian"); System.ou T.println ("Before Serializing "); System.out.println (" Emp ID: " + Emp.GetemployEID ()); System.out.println (" name: " + Emp.getName ())); System.out.println (" department: "" " + emp.getDepPartment ()); System.out.println ("National:" + Emp.getNationality ()); Out.println ("Serializing"); Try {FileoutPutstream Fileout = New FileoutPutstream ("Employeeee.Ser"); Stream (fileout); outstream.writeObject (EMP); outstream.close (); fileout.close ( );} Catch (IOEXCEPTION I) {I.printstacktrace ();} // Deserialize System.out.println ("****************"); );; TRY {FileInputStream FileIn = New FileInputStream ("Employeee.Ser"); ) in.readObject (); in.Close (); Filein.close ();} Catch (IOEXCEPTION I) {i.printstacktrace (); Return;} Catch (ClassNotFoundexception C) {System.out.println ("Employeeee Found Found" ); c.printstacktrace (); Return;} System. Out.println ("After Serializing"); System.out.println ("Emp ID:" + Emp.Getemployeeid ()); System.out.println ("name:" + EMP.GetName ()); m.out .println ("department:" + Emp.getDepPartment ()); System.out.println ("National:" + Emp.getNationality ());}}
run:
When you run the SerializeDeserializemain.java, you will get the following output. If the parent class is not serialized, then all instance variable values inherited in the parent class will be called Function is initialized. Here Name is inherited in Person, so during the process of deepery, name will be initialized to the default value.
Case 6 -If the parent class is serialized, but you don't need to inherit the class as serialized
If you do not want to inherit the class to serialize, then you need to implement the WriteObject () and ReadObject () methods, and need to throw out the abnormality of NotSerializableException.
Case 7 -Can the static variables serialize?
cannot. Because static variables are class levels, not object levels. When you serialize a object, you cannot serialize the static variable.
Summarize: