Last active
June 5, 2024 22:09
-
-
Save LeoAndo/3d511ab78c1e1bed1533a53f5acfe263 to your computer and use it in GitHub Desktop.
フィールドの修飾子transientのサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
class TransientSample01 { | |
public static void main(String[] args) { | |
final Person3 person = new Person3("Tanaka", 20, "Tokyo", "09012345678"); | |
System.out.println(person); // name=Tanaka, age=20, address=Tokyo, phone=09012345678 | |
final String fileName = "person.txt"; | |
// serialize Object to file | |
try { | |
final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName)); | |
oos.writeObject(person); | |
oos.close(); | |
} catch (IOException e) { | |
System.err.println(e.getMessage()); | |
} | |
// de-serialize Object from file | |
try { | |
final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName)); | |
Person3 deSerializeObject = (Person3) ois.readObject(); | |
ois.close(); | |
System.out.println(deSerializeObject); // name=Tanaka, age=0, address=null, phone=09012345678 | |
} catch (IOException | ClassNotFoundException e) { | |
System.err.println(e.getMessage()); | |
} | |
} | |
} | |
class Person3 implements Serializable { | |
private String name; | |
private transient int age; // シリアライズの対象外にする | |
private transient String address; // シリアライズの対象外にする | |
private String phone; | |
public Person3(String name, int age, String address, String phone) { | |
this.name = name; | |
this.age = age; | |
this.address = address; | |
this.phone = phone; | |
} | |
@Override | |
public String toString() { | |
return "Person3{" + | |
"name='" + name + '\'' + | |
", age=" + age + | |
", address='" + address + '\'' + | |
", phone='" + phone + '\'' + | |
'}'; | |
} | |
} |
フィールドの修飾子: transient
-
transient修飾子はシリアライズの対象外にしたいフィールド変数につける修飾子
-
シリアライズとは、Javaオブジェクトなどを、一定のデータ形式や変換規則に従って文字列やバイト列に変換し、ファイル保存したりデータの送受信などをできるようにすることを指す。
-
デシリアライズはデータを元の状態(java オブジェクト)に復元することを指す。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実行結果
transientあり (フィールド age, address)
transientなし