Java のシリアル化は、オブジェクトの状態をバイト ストリームに変換するメカニズムです。逆シリアル化はその逆のプロセスです。逆シリアル化を通じて、実際の Java オブジェクトがバイト ストリームからメモリ内に作成されます。このようなメカニズムはオブジェクト内に存続します。シリアル化によって作成されたバイト ストリームは、プラットフォームに依存しません。他のプラットフォームでは、あるプラットフォームでシリアル化されたオブジェクトを問題なく逆シリアル化できます。
無料ソフトウェア開発コースを始めましょう
Web 開発、プログラミング言語、ソフトウェア テスト、その他
したがって、シリアル化と逆シリアル化のプロセス全体は JVM に依存しません。クラス オブジェクトをシリアル化するには、java.io.Serializable インターフェイスを実装する必要があります。 Java でシリアライズ可能なのはマーカー インターフェイスです。実装するフィールドやメソッドはありません。このプロセスにより、オプトイン プロセスに似たクラスがシリアル化可能になります。
Java のシリアル化は、ObjectInputStream と ObjectOutputStream の 2 つのクラスによって実装されます。必要なのは、それらをファイルに保存したり、ネットワーク経由で送信したりできるように、それらをラッパーで覆うことだけです。
Java でのシリアル化の概念
上記のセクションで説明したシリアル化クラスである ObjectOutputStream クラスには、さまざまなデータ型を書き込むためのいくつかの書き込みメソッドが含まれていますが、最も一般的なメソッドは 1 つです。
public final void writeObject( Object x ) throws IOException
上記のメソッドを使用してオブジェクトをシリアル化できます。このメソッドはそれを出力ストリームにも送信します。同様に、ObjectInputStream クラスにはオブジェクトを逆シリアル化するためのメソッドが含まれています。
public final Object readObject() throws IOException, ClassNotFoundException
逆シリアル化メソッドは、ストリームからオブジェクトを取得し、それを逆シリアル化します。戻り値もオブジェクトなので、必要なのは、それを関連するデータ型にキャストすることだけです。
クラスのシリアル化を成功させるには、2 つの条件を満たす必要があります。
- お。クラスはシリアル化可能なインターフェイスを実装する必要があります。
- クラスのすべてのフィールドはシリアル化可能である必要があります。 1 つのフィールドでもシリアル化できない場合は、一時的としてマークする必要があります。
クラスがシリアル化可能かどうかを確認する必要がある場合、簡単な解決策は、クラスが java.io.Serializable メソッドを実装しているかどうかを確認することです。存在する場合、それはシリアル化可能です。そうでない場合は、そうではありません。オブジェクトをファイルにシリアル化するときは、ファイルに .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 中国語 Web サイトの他の関連記事を参照してください。

この記事では、Javaプロジェクト管理、自動化の構築、依存関係の解像度にMavenとGradleを使用して、アプローチと最適化戦略を比較して説明します。

この記事では、MavenやGradleなどのツールを使用して、適切なバージョン化と依存関係管理を使用して、カスタムJavaライブラリ(JARファイル)の作成と使用について説明します。

この記事では、カフェインとグアバキャッシュを使用してJavaでマルチレベルキャッシュを実装してアプリケーションのパフォーマンスを向上させています。セットアップ、統合、パフォーマンスの利点をカバーし、構成と立ち退きポリシー管理Best Pra

この記事では、キャッシュや怠zyなロードなどの高度な機能を備えたオブジェクトリレーショナルマッピングにJPAを使用することについて説明します。潜在的な落とし穴を強調しながら、パフォーマンスを最適化するためのセットアップ、エンティティマッピング、およびベストプラクティスをカバーしています。[159文字]

Javaのクラスロードには、ブートストラップ、拡張機能、およびアプリケーションクラスローダーを備えた階層システムを使用して、クラスの読み込み、リンク、および初期化が含まれます。親の委任モデルは、コアクラスが最初にロードされ、カスタムクラスのLOAに影響を与えることを保証します

この記事では、分散アプリケーションを構築するためのJavaのリモートメソッドの呼び出し(RMI)について説明します。 インターフェイスの定義、実装、レジストリのセットアップ、およびクライアント側の呼び出しを詳述し、ネットワークの問題やセキュリティなどの課題に対処します。

この記事では、ネットワーク通信のためのJavaのソケットAPI、クライアントサーバーのセットアップ、データ処理、リソース管理、エラー処理、セキュリティなどの重要な考慮事項をカバーしています。 また、パフォーマンスの最適化手法も調査します

この記事では、カスタムJavaネットワーキングプロトコルの作成を詳述しています。 プロトコルの定義(データ構造、フレーミング、エラー処理、バージョン化)、実装(ソケットを使用)、データシリアル化、およびベストプラクティス(効率、セキュリティ、メンテナ


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

WebStorm Mac版
便利なJavaScript開発ツール

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター
