首頁 > Java > java教程 > 主體

Java 中的序列化

王林
發布: 2024-08-30 16:06:52
原創
827 人瀏覽過

Java中的序列化是一種將物件的狀態轉換為位元組流的機制。反序列化是其逆過程。透過反序列化,可以從位元組流在記憶體中建立實際的 Java 物件。這種機制持續存在於物件中。透過序列化創建的位元組流不依賴任何平台。任何其他平台都可以反序列化在一個平台上序列化的對象,不會有問題。

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

因此,序列化和反序列化的整個過程是獨立於JVM的。要序列化類別對象,必須實作 java.io.Serialized 介面。 Java中的Serializing是一個標記介面。它沒有要實現的字段或方法。此過程使類別可序列化,類似於選擇加入過程。

Java中的序列化是由ObjectInputStream和ObjectOutputStream這兩個類別實現的。所需要的只是將它們包裝,以便將它們保存到文件或透過網路發送。

Java 序列化的概念

上一節提到的序列化類別ObjectOutputStream包含多種用於寫入各種資料類型的寫入方法,但其中一種方法是最受歡迎的。

public final void writeObject( Object x ) throws IOException
登入後複製

可以使用上面的方法來序列化一個物件。此方法還將其傳送到輸出流。同樣,ObjectInputStream類別包含物件反序列化的方法。

public final Object readObject() throws IOException, ClassNotFoundException
登入後複製

反序列化方法從流中檢索物件並對其進行反序列化。傳回值又是一個對象,因此所需要做的就是將其轉換為相關的資料類型。

成功序列化類別必須滿足兩個條件。

  • io.該類別必須實作可序列化介面。
  • 類別的所有欄位都必須是可序列化的。如果甚至有一個欄位不可序列化,則應將其標記為瞬態。

如果有人需要檢查一個類別是否可序列化,簡單的解決方案是檢查該類別是否實作了 java.io.Serializing 方法;如果是,則它是可序列化的。如果不是,那就不是。人們應該注意到,當物件序列化到檔案時,標準做法是為檔案賦予 .ser 副檔名。

方法

如果類別包含這些方法,它們將用於 Java 中的序列化。

1. 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. 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.

以上是Java 中的序列化的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板