Rumah  >  Artikel  >  Java  >  Serialisasi di Jawa

Serialisasi di Jawa

王林
王林asal
2024-08-30 16:06:52789semak imbas

Siri dalam Java ialah mekanisme yang menukar keadaan objek kepada aliran bait. Penyahserialisasian adalah proses sebaliknya. Melalui penyahserialisasian, objek Java sebenar dicipta dalam ingatan daripada aliran bait. Mekanisme sedemikian berterusan dalam objek. Strim bait yang dibuat daripada penyirian tidak bergantung pada mana-mana platform. Mana-mana platform lain boleh menyahsiri objek yang disiri pada satu platform tanpa masalah.

Mulakan Kursus Pembangunan Perisian Percuma Anda

Pembangunan web, bahasa pengaturcaraan, ujian perisian & lain-lain

Oleh itu, keseluruhan proses bersiri dan penyahserikatan adalah bebas JVM. Untuk menyerikan objek kelas, anda mesti melaksanakan antara muka java.io.Serializable. Boleh bersiri dalam Java ialah antara muka penanda. Ia tidak mempunyai bidang atau kaedah untuk dilaksanakan. Proses ini menjadikan kelas boleh bersiri, menyerupai proses Ikut serta.

Serialization dalam Java dilaksanakan oleh dua kelas ObjectInputStream dan ObjectOutputStream. Apa yang diperlukan ialah mempunyai pembungkus di atasnya supaya ia boleh disimpan ke fail atau dihantar melalui rangkaian.

Konsep Pensiri dalam Java

Kelas ObjectOutputStream, kelas bersiri yang disebut dalam bahagian di atas, mengandungi beberapa kaedah penulisan untuk menulis pelbagai jenis data, tetapi satu kaedah adalah yang paling popular.

public final void writeObject( Object x ) throws IOException

Anda boleh menggunakan kaedah di atas untuk mensiri objek. Kaedah ini juga menghantarnya ke aliran keluaran. Dengan cara yang sama, kelas ObjectInputStream mengandungi kaedah untuk penyahserikatan objek.

public final Object readObject() throws IOException, ClassNotFoundException

Kaedah penyahserikatan mendapatkan semula objek daripada aliran dan menyahsiri yang sama. Nilai pulangan sekali lagi ialah objek, jadi semua yang diperlukan ialah menghantarnya ke jenis data yang berkaitan.

Dua syarat mesti dipenuhi untuk menjayakan siri kelas.

  • io. Kelas mesti melaksanakan antara muka boleh bersiri.
  • Semua medan kelas mesti boleh bersiri. Jika walaupun satu medan tidak boleh bersiri, ia harus ditandakan sementara.

Jika seseorang perlu menyemak sama ada kelas boleh bersiri, penyelesaian mudah ialah menyemak sama ada kelas itu melaksanakan kaedah java.io.Serializable; jika ia berlaku, maka ia boleh bersiri. Jika ia tidak, maka ia tidak. Seseorang harus menyedari bahawa apabila mensiri objek ke fail, amalan standard adalah untuk memberikan fail sambungan .ser.

Kaedah

Jika kelas mengandungi kaedah ini, ia digunakan untuk bersiri dalam Java.

1. Kaedah Pensirian dalam 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. Kaedah Deserialisasi dalam 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);
}
}

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();
}
}
}

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

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.

Atas ialah kandungan terperinci Serialisasi di Jawa. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Input Pengguna JavaArtikel seterusnya:Input Pengguna Java