Learn serialization mechanism in Java?

Serialize and de-serialize in Java

Et de serialize Java-in serialize,,en,quod prorsus contrarium est processus deserialization,,en,ubi rursus conversos in ea sequentes bytes,,en,Magni momenti in puncto ad note est quod reconditum latet in current statu ad statum illum solum, et reversed,,en,ordo secundum rationem explorare poterimus serialization Java et opus aliquod exemplum coding,,en,Quare indigemus serialization,,en,In Java obiecti omnia ex persona eius,,en,per applicationem Java,,en,solus illud non stare,,,en,vel aliam rem,,en,vos postulo ut tractaret cum objects,,en,Quorum ista sunt civitates,,en,Nihil autem civitatibus quae data valorem, aut in aliqua parte temporis continet,,,en,ac subinde variare,,en,In application,,en,si opus condo notitia,,en,possumus et repones intra ianuas database ratio lima,,en

Overview:

One of the fundamental strength of Java is its serialization mechanism. This is basically serialization of Java objects, where the object is persisted as a sequence of bytes. The persistent storage can be file system, database or streams. And, deserialization is just the reverse process, where the sequences of bytes are again converted back into objects. The important point to note is that the object is stored in its current state and reversed back to that state only.

In this article, we will try to explore the core concepts of Java object serialization and also work on some coding examples.


 

Why we need serialization?

Everything in Java is represented as objects. So, in a Java application, be it stand-alone, enterprise or in some other form, you need to deal with objects. These objects are having their own states (states are nothing but the value or data it contains at any point of time) and it varies from time to time.

In an application, if we need to store data, we can store it in a database or file system (in forma files,,en,ubicumque tunc recuperare illa requiratur,,en,hoc est rudis notitia repono et tractantem typically,,en,si nos postulo ut congregem ad object,,en,et status ejus cum current valorem,,en,non possumus uti vel file systema directe database,,en,Eo quod non intellegunt,,en,ita,,en,Nos postulo ut repones intra ianuas forma bytes,,en,Hoc mechanism enim referendo etiam cum necesse est transferre super network object,,en,est quaestio - ',,en,Quomodo autem id praestare opus,,,en,Haec quaestio est solutio,,en,Potest et ita finire, ut protocol,,en,quae potest esse ab aliquo, aut de partium serialize usque ad object-serialize,,en,Post duos plurimum momenti sunt ad usus late serialization pro quo,,en,Obdurat obiecti in repono,,en,lima ratio,,en,amnis,,en,Objects in serie network,,en,Quidam conceptibus memoratis,,en). And, then retrieve it whenever required. autem, this is typically handling and storing the raw data.

Now, if we need to store an object (with its current state and value) we cannot use database or file system directly. Because they do not understand object, so, we need to store it in the form of bytes. This mechanism is also applicable when we need to transfer an object over network.







autem, the question is – ‘How do we perform this task’? Serialization is the solution to this problem. It can also be defined as a protocol, which can be used by any party to serialize or de-serialize an object.

Following are the two most important purpose for which serialization is widely used.

  • Persists objects in storage (Database, file system, stream)
  • Transfer Objects over network

Some related concepts

Ante movere ad proximam sectiones ex codice exempla ac praevalentes machinationes serialization,,en,et nos debemus intelligere aliquam basic conceptus technica usus est in processus serialization,,en,serialVersionUID,,en,Plerumque enim hic idem obiectum serialized,,en,Est usus ut a serialized et obiecti esse de eodem, serialized,,en,UID et haec Ab omnibus oportet aliquando usus est, quia ad refactoring,,en,More Details inveniri potest,,,en,mollis Venalicium,,en,Rem peragendam aut serializable serialization Java,,en,opus ad effectum deducendi,,en,Interface est Serializable determinatione,,en,id est an interface sine agris et modi,,en,ad aliquam specialem effectum ducenda mores,,en,Sunt aliae quoque available in venalicium interfaces Java,,en,Caducae Match,,en,Hoc est valde magni momenti in keyword Java,,en, we must understand some basic technical concepts used in the serialization process.

serialVersionUID: This is basically the identification of a serialized object. It is used to ensure that the serialized and de-serialized objects are same. Sometime this UID is also used for refactoring purpose. More details can be found here.

Marker Interface: To implement serialization in Java or making an object serializable, you need to implement Serializable interface. Serializable is a marker interface, which means it is an interface without any fields and methods, for implementing some special behaviour. There are also other marker interfaces available in Java.

Transient Keyword: This is a very important keyword in Java. Non opus est, ut congregem ad vitare aliqua ex parte obiecti et sensitive habet agrorum cuius notitia amo promeritum pecto numerus,,en,password etc.,,en,Nos iustus postulo ut agri eorum define,,en,'vagi,,en,et non vult salvari per provincias processus serialization,,en,Fluvius classes objiciat,,en,Duae res, et de gurgite classes serialization serialization processu amet,,en,Et illi ObjectOutputStream ObjectInputStream,,en,Nos mos reprehendo in implementation in sectione sequenti codice sample,,en,Quam serialization opera - Quidam codice Exempla,,en,In hoc coding exemplum habebimus infra, de quibus tres classes Java,,en,genus repraesentat obiectum serialized Java,,en,Discipulus serializing genere quod Java,,en,Discipulus quod salvetur de genere bonorum extrahere Java,,en, password etc. Here, we just need to define those fields as ‘transient’, and it will not allow those fields to be saved during the serialization process.

Object Stream classes: Two object stream classes are very important for serialization and de-serialization process. Those are ObjectOutputStream and ObjectInputStream. We will check the implementation in the following code sample section.

How serialization works – Some code Examples

In this coding example we will have three Java classes as mentioned below.

  • java class representing the object to be serialized
  • java class for serializing Student object
  • java class to extract the values from the saved Student object

Discipulus hoc est genus in aliquo agrorum pertinet,,en,Placere note quod ',,en,pwd ',,en,ager, sicut alibi,,,en,malum transiens,,,en,ut propter salutem parte obiecti,,en,Discipulus autem id quod aliis salvabuntur de,,en,Discipulo genus codice sample,,en,Discipulus publica genere ad effectum adducit java.io.Serializable,,en,Gloria publico nomine,,en,Gloria inscriptio palam,,en,public String userId,,en,public String transit pwd,,en,publica inanis objectCheck,,en,details discipulus,,en,oratio ,,en,userId,,en,Discipulus serialize disposito, ut ostensum est genus de quo inferius,,en,Studiosus object quod gignit et salvum facere quod lima in nomine ',,en,student.ser ',,en,ratio ad locorum files,,en,Discipulus classis obiectum serializing,,en,genus publico SerializeExample,,en,= Sancti nova discipulus discipulus,,en,st.name =,,en,Allen,,en,st.address =,,en,TX,,en,st.userId =,,en,Aln,,en,st.pwd =,,en,Aln123 $,,ar,Create output lima amnis,,en. Please note that the ‘pwd’ field is marked as ‘transient’ to avoid saving it as a part of the object. The other fields will be saved as part of the Student object.







Listing1: Student class sample code

[Codicem]

public class Student implements java.io.Serializable

{

public String name;

public String address;

public String userId;

public transient String pwd;

public void objectCheck()

{

System.out.println(“Student details ” + nomen + ” ” + address ” “+ userId);

}

}

[/Codicem]

Now, the 2nd class is designed to serialize Student object as shown below. It creates a Student object and save it in a file named ‘student.ser’ in the local files system.

Listing2: Serializing Student class object

[Codicem]

import java.io.*;

public class SerializeExample

{

static vacuum publicum principale(String [] args)

{

Student st = new Student();

st.name = “Allen”;

st.address = “TX, USA”;

st.userId = “Aln”;

st.pwd = “Aln123$”;

experiri

{

//Create file output stream

FileOutputStream fileOutStr =,,en,student.ser,,en,Quod creavit unda output quod scribam,,en,ObjectOutputStream objOutStr = Novum ObjectOutputStream,,en,fileOutStr,,en,objOutStr.writeObject,,en,Clauderent fluminum omnium,,en,objOutStr.close,,en,fileOutStr.close,,en,System.out.printf,,en,Serialized notitia quod lima servata est,,en,Output de hoc genere ostensum est inferius,,en,Ostendens output serialization,,en,Discipulus classis obiectum constituunt extrahere de bonis, a salvato serialize,,en,Et extractum values ​​ut ostensum est super consolatorium Java,,en,Discipulus De obiecto serializing,,en,genus publico DeserializeExample,,en,Create discipulus object,,en,Nullum, studiosum s =,,en,FileInputStream fileInStr = Novum FileInputStream,,en,ObjectInputStream objInStr = Novum ObjectInputStream,,en,fileInStr,,en,= Sancti,,en,objInStr.readObject,,en,objInStr.close,,en,fileInStr.close,,en,ClassNotFoundException cexp,,en,Genus studiosum non inveni,,en,cexp.printStackTrace,,en,Discipulus Deserialized,,en,st.name,,en,st.address,,en,Sed rutrum sapien id,,en,st.userId,,en,st.pwd,,en

new FileOutputStream(“student.ser”);

//Create object output stream and write object

ObjectOutputStream objOutStr = new ObjectOutputStream(fileOutStr);

objOutStr.writeObject(st);

//Close all streams

objOutStr.close();

fileOutStr.close();

System.out.printf(“Serialized data is saved in a file – student.ser”);

}capere(IOException exp)

{

exp.printStackTrace();

}

}

}

[/Codicem]

Output from this class is shown below.

Serialization

Image 1: Showing serialization output

The 3rd class is designed to de-serialize the saved Student object and extract the values from it. The extracted values will be shown on the Java console.


 

Listing3: De-serializing Student object

[Codicem]

import java.io.*;

public class DeserializeExample

{

static vacuum publicum principale(String [] args)

{

//Create student object

Student st = null;

experiri

{

FileInputStream fileInStr = new FileInputStream(“student.ser”);

ObjectInputStream objInStr = new ObjectInputStream(fileInStr);

st = (Student) objInStr.readObject();

objInStr.close();

fileInStr.close();

}capere(IOException exp)

{

exp.printStackTrace();

return;

}capere(ClassNotFoundException cexp)

{

System.out.println(“Student class not found”);

cexp.printStackTrace();

return;

}

System.out.println(“Deserialized Student…”);

System.out.println(“Nomen: ” + st.name);

System.out.println(“Address: ” + st.address);

System.out.println(“User Id: ” + st.userId);

System.out.println(“Password: ” + st.pwd);

}

}

[/Codicem]

Output from this class is shown below. Placere note quod non output valorem imprimendi in password,,en,ut dictum est transitoria,,en,-Showing de output serialization,,en,Quidam in vita reali implementations,,en,Venite vultus ad aliquid habent de vita reali implementations de serialization,,en,Non intelligis te, et auxiliatus est momenti atque usus adsiduitate object,,en,In quo statu cum cogitant de ludum application sit amet ipsum,,en,reliquit ullum punctum temporis ad ludum cum user,,en,Si quis ad punctum temporis,,en,per applicationem, aut non penitus non operatur,,en,media usus utentis sit aliquod divelli,,en,Reposita est haec actio fit medium rei serialized,,en,et statutum est solummodo redintegrari denuo nexum,,en,quo eodem ille usura operatio possit,,en, as it was declared as transient.

De-serialization

Image 2: Showing de-serialization output

Some real life implementations

In this section, let us have a look at some of the real life implementations of serialization. It will help you understand the importance and the usage of object persistence.

  • Think of a game application where the state is very important. Now, when a user left the game at any point of time, the state is serialized and stored in some type of storage. While the user wants to re-start the game again, same state of the object is recreated by the process of de-serialization. So, nothing is lost in the whole process.
  • The other important example is ATM application. When a user request some withdrawal from an ATM machine (which is the client), the request is sent to the server as a serialized object. On the server end, the reverse process (de-serialization) is executed and the action is performed. This is an example of how serialization works over network communication.
  • Stock market update is another example where the update is stored as a serialized object and served to the client whenever required.
  • In any web application, the user session information is very important to maintain. Quod, if at any point of time, the application fails or internet does not work, the user is disconnected from the application in the middle of some activity. Now, this half-done activity is stored as a serialized object, and restored when connection is established again. As a result, the user can continue from the same point where he left his activity.

Conclusio:

Java serialization est valde maximus pluma ut discas,,en,de quibus per singula apud nos in serialization pertinet ad rationem,,en,Nos have quoque ostendere, quam explicavit unum exemplum coding opera serialization,,en,Et altius investigetur aliqua exempli gratia, nunc mixta praeter officia praestare,,en,natura est flexibile serialization,,en,sed developers postulo scio tips et obtusum ad id apte ad effectum deducendi,,en,Spero te pascam duce progredi dictum,,en,techalpine.com/learn-serialization-mechanism-in-java,,en. In this article, we have discussed serialization in details along with its relevant concepts. We have also explained one coding example to show how serialization works. The example can be enhanced or modified to perform addition tasks. Overall, serialization is very flexible in nature, but the developers need to know the tricks and tips to implement it properly. Hope this article will provide you a guidance to move forward.








 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share