Javaのtransientキーワード
一時的な で使用される変数修飾子です。 連載化 。シリアル化時に、特定の変数の値をファイルに保存したくない場合は、次を使用します。 一時的な キーワード。 JVM に出会ったとき 一時的な キーワードを指定すると、変数の元の値が無視され、その変数のデータ型のデフォルト値が保存されます。 一時的な キーワードは、セキュリティ上の制約を満たすために重要な役割を果たします。プライベート データをファイルに保存したくない実際の例はさまざまです。別の使い方 一時的な キーワードは、人の年齢、現在の日付など、他のシリアル化されたオブジェクトやシステムを使用して値を計算/導出できる変数をシリアル化することではありません。実際には、すべてのシリアル化でオブジェクトの状態をファイルに保存した後、インスタンスの状態を表すフィールドのみをシリアル化します。使うのが良い習慣です 一時的な keyword with private confidential fields of a class during serialization. Java
// A sample class that uses transient keyword to // skip their serialization. class Test implements Serializable { // Making password transient for security private transient String password ; // Making age transient as age is auto- // computable from DOB and current date. transient int age ; // serialize other fields private String username email ; Date dob ; // other code }
一時的および静的: 以来 静的 フィールドはオブジェクトの状態の一部ではないため、使用/使用による影響はありません。 一時的な 静的変数を含むキーワード。ただし、コンパイルエラーは発生しません。 一時的および最終的: 最終変数はその値によって直接シリアル化されるため、最終変数を次のように宣言しても使用/影響はありません。 一時的な . There is no compile-time error though. Java // Java program to demonstrate transient keyword // Filename Test.java import java.io.* ; class Test implements Serializable { // Normal variables int i = 10 j = 20 ; // Transient variables transient int k = 30 ; // Use of transient has no impact here transient static int l = 40 ; transient final int m = 50 ; public static void main ( String [] args ) throws Exception { Test input = new Test (); // serialization FileOutputStream fos = new FileOutputStream ( 'abc.txt' ); ObjectOutputStream oos = new ObjectOutputStream ( fos ); oos . writeObject ( input ); // de-serialization FileInputStream fis = new FileInputStream ( 'abc.txt' ); ObjectInputStream ois = new ObjectInputStream ( fis ); Test output = ( Test ) ois . readObject (); System . out . println ( 'i = ' + output . i ); System . out . println ( 'j = ' + output . j ); System . out . println ( 'k = ' + output . k ); System . out . println ( 'l = ' + output . l ); System . out . println ( 'm = ' + output . m ); } }
Output : i = 10 j = 20 k = 0 l = 40 m = 50