Learn serialization mechanism in Java?

Serialize and de-serialize in Java

Java'da seri hale getir ve serileştir,,en,Java'nın temel güçlerinden biri seri hale getirme mekanizmasıdır.,,en,Bu temelde Java nesnelerinin serileştirilmesidir.,,en,Nesnenin bir bayt dizisi olarak kaldığı yer,,en,Kalıcı depolama dosya sistemi olabilir,,en,veritabanı veya akışları,,en,serileştirme sadece ters işlemdir,,en,Bayt dizileri tekrar nesnelere dönüştürülür.,,en,Dikkat edilmesi gereken önemli nokta, nesnenin mevcut durumunda saklanması ve yalnızca bu duruma geri döndürülmesidir.,,en,Java nesne serileştirmesinin temel kavramlarını keşfetmeye çalışacağız ve bazı kodlama örneklerinde de çalışacağız.,,en,Neden seri hale getirmeye ihtiyacımız var?,,en,Java'daki her şey nesneler olarak temsil edilir,,en,Java uygulamasında,,en,yalnız mı,,en,kurumsal veya başka bir biçimde,,en,nesnelerle uğraşmak zorundasın,,en

Genel bakış:

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. Bu nesneler kendi eyaletlerine sahipler,,en,durumlar, herhangi bir zamanda içerdiği değer veya veriden başka bir şey değildir,,en,ve zaman zaman değişiyor,,en,Bir uygulamada,,en,veri depolamamız gerekirse,,en,bir veritabanında veya dosya sisteminde saklayabiliriz,,en,dosya şeklinde,,en,daha sonra gerektiğinde geri alın,,en,Bu tipik olarak ham verileri işlemek ve saklamaktır,,en,bir nesneyi saklamak gerekirse,,en,mevcut durumu ve değeri ile,,en,veritabanı veya dosya sistemini doğrudan kullanamıyoruz,,en,Çünkü nesneleri anlamıyorlar,,en,yani,,en,bunu bayt biçiminde saklamamız gerekiyor,,en,Bu mekanizma, bir nesneyi ağ üzerinden aktarmamız gerektiğinde de uygulanabilir.,,en,soru - ',,en,Bu görevi nasıl uygularız?,,en,bu sorunun çözümü,,en,Ayrıca bir protokol olarak tanımlanabilir,,en (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 the form of files). And, then retrieve it whenever required. But, 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.







But, the question is – ‘How do we perform this task’? Serialization is the solution to this problem. It can also be defined as a protocol, herhangi bir taraf tarafından bir nesneyi serileştirmek veya serileştirmek için kullanılabilir,,en,Aşağıdakiler, serileştirmenin yaygın olarak kullanıldığı iki en önemli amaçtır.,,en,Depodaki nesneler devam ediyor,,en,dosya sistemi,,en,Akış,,en,Nesneleri ağ üzerinden aktar,,en,Bazı ilgili kavramlar,,en,Serileştirme mekanizmaları ve kod örnekleri üzerinde sonraki bölümlere geçmeden önce,,en,serileştirme sürecinde kullanılan bazı temel teknik kavramları anlamalıyız,,en,serialVersionUID,,en,Bu temelde seri hale getirilmiş bir nesnenin tanımlanmasıdır,,en,Seri hale getirilmiş ve serileştirilmiş nesnelerin aynı olmasını sağlamak için kullanılır,,en,Bazen bu UID ayrıca yeniden amaçlandırma amacı için kullanılır.,,en,Daha fazla detay bulunabilir,,en,Marker Arayüzü,,en,Java'da serileştirmeyi uygulamak veya seri hale getirilebilir bir nesne yapmak,,en,uygulamak zorundasın,,en,Seri hale getirilebilir bir işaretçi arayüzü,,en.

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

Before moving into the next sections on serialization mechanisms and code samples, 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. There may be a need to store a part of an object and avoid some fields which may contain sensitive information like credit card number, 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

Bu kodlama örneğinde, aşağıda belirtilen üç Java sınıfına sahip olacağız.,,en,serileştirilecek nesneyi temsil eden java sınıfı,,en,Öğrenci nesnesini serileştirmek için java sınıfı,,en,kaydedilmiş Öğrenci nesnesinden değerleri ayıklamak için java sınıfı,,en,Aşağıdaki bazı ilgili alanlarla Öğrenci sınıfı,,en,Lütfen ‘,,en,‘pwd,,en,alan marked olarak işaretlenir,,en,geçici',,en,nesnenin bir parçası olarak kaydetmekten kaçınmak için,,en,Diğer alanlar Öğrenci nesnesinin bir parçası olarak kaydedilecek,,en,Öğrenci sınıfı örnek kodu,,en,kamu sınıfı Öğrenci java.io.Serializable uygular,,en,genel Dize adı,,en,genel Dize adresi,,en,Genel Dize userId,,en,herkese açık geçici String pwd,,en,public void objectCheck,,en,adres ,,en,Kullanıcı adı,,en,sınıf, aşağıda gösterildiği gibi Öğrenci nesnesini serileştirmek için tasarlanmıştır,,en,Bir Öğrenci nesnesi oluşturur ve ‘adlı bir dosyaya kaydeder.,,en.

  • 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

Following is the Student class with some relevant fields. 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

[kod]

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 ” + isim + ” ” + address ” “+ userId);

}

}

[/kod]

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’,,en,yerel dosya sisteminde,,en,Serializing Student sınıfı nesnesi,,en,public class SerializeExample,,en,Öğrenci st = Yeni Öğrenci,,en,st.name =,,en,Allen,,en,st.address =,,en,Teksas,,en,st.userId =,,en,Aln,,en,st.pwd =,,en,Aln123 $,,ar,Dosya çıkış akışı oluştur,,en,FileOutputStream fileOutStr =,,en,student.ser,,en,Nesne çıktı akışı oluşturma ve nesne yazma,,en,ObjectOutputStream objOutStr = yeni ObjectOutputStream,,en,fileOutStr,,en,objOutStr.writeObject,,en,Tüm akışları kapat,,en,objOutStr.close,,en,fileOutStr.close,,en,System.out.printf,,en,Seri hale getirilmiş veriler bir dosyaya kaydedilir,,en,Bu sınıfın çıkışı aşağıda gösterilmiştir.,,en,Serileştirme çıktısı gösteriliyor,,en,sınıf, kaydedilen Öğrenci nesnesini serileştirmek ve bunlardan değerleri ayıklamak için tasarlanmıştır,,en,Ayıklanan değerler Java konsolunda gösterilecektir.,,en,Öğrenci nesnesini dizileştirme,,en,Devlet bir dizi depolamada dizileşir ve depolanır,,en,Kullanıcı oyunu tekrar başlatmak istediğinde,,en in the local files system.

Listing2: Serializing Student class object

[kod]

import java.io. *;

public class SerializeExample

{

public static void main(Dizi [] args)

{

Student st = new Student();

st.name = “Allen”;

st.address = “TX, Amerika Birleşik Devletleri”;

st.userId = “Aln”;

st.pwd = “Aln123$”;

denemek

{

//Create file output stream

FileOutputStream fileOutStr =

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”);

}yakalamak(IOException exp)

{

exp.printStackTrace();

}

}

}

[/kod]

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

[kod]

import java.io. *;

public class DeserializeExample

{

public static void main(Dizi [] args)

{

//Create student object

Student st = null;

denemek

{

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

ObjectInputStream objInStr = new ObjectInputStream(fileInStr);

st = (Student) objInStr.readObject();

objInStr.close();

fileInStr.close();

}yakalamak(IOException exp)

{

exp.printStackTrace();

return;

}yakalamak(ClassNotFoundException cexp)

{

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

cexp.printStackTrace();

return;

}

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

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

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

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

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

}

}

[/kod]

Output from this class is shown below. Please note that the output does not print the value of the password, 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, Nesnenin aynı durumu, serileştirme işlemiyle yeniden oluşturulur,,en,tüm süreçte hiçbir şey kaybolmaz,,en,Diğer önemli örnek ATM uygulamasıdır.,,en,Bir kullanıcı bir ATM makinesinden para çekme isteğinde bulunduğunda,,en,müşteri olan,,en,istek seri hale getirilmiş bir nesne olarak sunucuya gönderilir,,en,Sunucuda,,en,ters işlem,,en,de-serileştirme,,zh-CN,yürütülür ve eylem gerçekleştirilir,,en,Bu, serileştirmenin ağ iletişimi üzerinde nasıl çalıştığının bir örneğidir,,en,Borsa güncellemesi, güncellemenin seri hale getirilmiş bir nesne olarak saklandığı ve gerektiğinde müşteriye sunulduğu başka bir örnektir.,,en,Herhangi bir web uygulamasında,,en,Kullanıcı oturumu bilgileri korumak için çok önemlidir,,en,herhangi bir zamanda,,en,uygulama başarısız oluyor veya internet çalışmıyor,,en. 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. Because, if at any point of time, the application fails or internet does not work, Kullanıcı bazı etkinliklerin ortasında uygulama ile bağlantısı kesildi,,en,Bu yarı bitmiş etkinlik seri hale getirilmiş bir nesne olarak saklanır,,en,ve bağlantı tekrar kurulduğunda geri yüklendi,,en,Kullanıcı faaliyetinden ayrıldığı yerden devam edebilir,,en,Java serileştirme öğrenmek için çok önemli bir özellik,,en,ilgili kavramlarla birlikte serileştirmeyi ayrıntılı olarak tartıştık,,en,Serileştirmenin nasıl çalıştığını göstermek için bir kodlama örneğini de açıkladık.,,en,Örnek, ekleme görevlerini gerçekleştirmek için geliştirilebilir veya değiştirilebilir,,en,serileştirme doğada çok esnektir,,en,ama geliştiricilerin düzgün bir şekilde uygulamak için püf noktaları ve ipuçlarını bilmesi gerekiyor,,en,Umarım bu yazı size ileriye doğru ilerlemek için bir rehber sağlayacaktır.,,en,techalpine.com/learn-serialization-mechanism-in-java,,en. 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.

Sonuç:

Java serialization is a very important feature to learn. 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