Java transient 關鍵字
示例
transient
關鍵字阻止屬性被序列化
import java.io.*;
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.fname = "John";
person.lname = "Doe";
person.age = 24;
person.accessCode = 5044;
// Serialize the object
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
ObjectOutputStream objOut = new ObjectOutputStream(output);
objOut.writeObject(person);
} catch (IOException e) {}
// Deserialize the object
Person person2 = new Person();
try {
ObjectInputStream objIn = new ObjectInputStream(new ByteArrayInputStream(output.toByteArray()));
person2 = (Person)objIn.readObject();
} catch(Exception e) {}
// Print the deseralized object
System.out.println("First name: " + person2.fname);
System.out.println("Last name: " + person2.lname);
System.out.println("Age: " + person2.age);
System.out.println("Access code: " + person2.accessCode);
}
}
class Person implements Serializable {
String fname = "John";
String lname = "Doe";
int age = 24;
transient int accessCode = 0;
}
定義和用法
transient
關鍵字是一個修飾符,它告訴 Java 在序列化物件時忽略某個屬性。
相關頁面
在我們的 Java 修飾符教程 中瞭解更多關於修飾符的資訊。