Maison > Java > javaDidacticiel > le corps du texte

Sérialisation en Java

王林
Libérer: 2024-08-30 16:06:52
original
786 Les gens l'ont consulté

La sérialisation en Java est un mécanisme qui convertit l'état d'un objet en un flux d'octets. La désérialisation est son processus inverse. Grâce à la désérialisation, un objet Java réel est créé en mémoire à partir d'un flux d'octets. Un tel mécanisme persiste dans l’objet. Le flux d'octets ainsi créé à partir de la sérialisation ne dépend d'aucune plate-forme. Toute autre plateforme peut désérialiser l'objet sérialisé sur une plateforme sans problème.

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Ainsi, l'ensemble du processus de sérialisation et de désérialisation est indépendant de la JVM. Pour sérialiser un objet de classe, vous devez implémenter l'interface java.io.Serializing. Sérialisable en Java est une interface de marqueur. Il n’a aucun champ ni méthode à implémenter. Ce processus rend une classe sérialisable, ressemblant à un processus Opt-In.

La sérialisation en Java est implémentée par les deux classes ObjectInputStream et ObjectOutputStream. Il suffit de les recouvrir d'un wrapper afin qu'ils puissent être enregistrés dans un fichier ou envoyés sur un réseau.

Concept de sérialisation en Java

La classe ObjectOutputStream, une classe de sérialisation mentionnée dans la section ci-dessus, contient plusieurs méthodes d'écriture pour écrire différents types de données, mais une méthode est la plus populaire.

public final void writeObject( Object x ) throws IOException
Copier après la connexion

Vous pouvez utiliser la méthode ci-dessus pour sérialiser un objet. Cette méthode l'envoie également au flux de sortie. De la même manière, la classe ObjectInputStream contient la méthode de désérialisation des objets.

public final Object readObject() throws IOException, ClassNotFoundException
Copier après la connexion

La méthode de désérialisation récupère l'objet d'un flux et le désérialise. La valeur de retour est à nouveau un objet, il suffit donc de la convertir en un type de données pertinent.

Deux conditions doivent être remplies pour une sérialisation réussie d'une classe.

  • io. La classe doit implémenter une interface sérialisable.
  • Tous les champs de la classe doivent être sérialisables. Si même un champ n'est pas sérialisable, il doit être marqué comme transitoire.

Si quelqu'un a besoin de vérifier si une classe est sérialisable, la solution simple est de vérifier si la classe implémente la méthode java.io.Seriallessly ; si c'est le cas, alors il est sérialisable. Si ce n’est pas le cas, alors ce n’est pas le cas. Il convient de noter que lors de la sérialisation d'un objet dans un fichier, la pratique standard consiste à donner au fichier une extension .ser.

Méthodes

Si la classe contient ces méthodes, elles sont utilisées pour la sérialisation en Java.

1. Méthode de sérialisation en Java

Method Description
public final void writeObject (Object obj) throws IOException {} This will write the specified object to the ObjectOutputStream.
public void flush() throws IOException {} This will flush the current output stream.
public void close() throws IOException {} This will close the current output stream.

2. Méthode de désérialisation en Java

Method Description
public final Object readObject() throws IOException, ClassNotFoundException{} This will read an object from the input stream.
public void close() throws IOException {} This will close ObjectInputStream.

Example of Serialization in Java

An example in Java is provided here to demonstrate how serialization works in Java. We created an Employee class to study some features, and the code is provided below. This employee class implements the Serializable interface.

public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a letter to " + name + " " + address);
}
}
Copier après la connexion

When this program finishes executing, it will create a file named employee.ser. This program does not provide a guaranteed output, rather it is for explanatory purposes only, and the objective is to understand its use and to work.

import java.io.*;
public class SerializeDemo {
public static void main(String [] args) {
Employee e = new Employee();
e.name = "Rahul Jain";
e.address = "epip, Bangalore";
e.SSN = 114433;
e.number = 131;
try {
FileOutputStream fileOut =
new FileOutputStream("https://cdn.educba.com/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
Copier après la connexion

The below-described DeserializeDemo program deserializes the above Employee object created in the Serialize Demo program.

import java.io.*;
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("https://cdn.educba.com/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class is not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}
Copier après la connexion

Output:

Deserialized Employee…

Name: Rahul Jain

Address: epip, Bangalore

SSN: 0

Number:131

Some important points related to the program above are provided below:

  • The try/catch block above tries to catch a ClassNotFoundException. This is declared by the readObject() method.
  • A JVM can deserialize an object only if it finds the bytecode for the class.
  • If the JVM does not find a class during the deserialization, it will throw ClassNotFoundException.
  • The readObject () return value is always cast to an Employee reference.
  • When the object was serialized, the SSN field had an initial value of 114433, which was not sent to the output stream. Because of the same, the deserialized Employee SSN field object is 0.

Conclusion

Above, we introduced serialization concepts and provided examples. Let’s understand the need for serialization in our concluding remarks.

  • Communication: If two machines that are running the same code need to communicate, the easy way out is that one machine should build an object containing information that it would transmit and then serialize that object before sending it to the other machine. The method may not be perfect, but it accomplishes the task.
  • Persistence: If you want to store the state of an operation in a database, you first serialize it to a byte array and then store the byte array in the database for retrieval later.
  • Deep Copy: If creating a replica of an object is challenging and writing a specialized clone class is difficult, then the goal can be achieved by serializing the object and then de-serializing it into another object.
  • Cross JVM Synchronization: JVMs running on different machines and architectures can be synchronized.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!