transient 修飾實例變量,標記該字段**不參與 Java 默認序列化過程**。反序列化時,該字段將被賦予默認值 (對象為 null,基本類型為 0/false)。
import java.io.*;
public class TransientDemo implements Serializable {
private static final long serialVersionUID = 1L;
private transient String name; // 不序列化
private String password; // 序列化
public TransientDemo(String name, String password) {
this.name = name; this.password = password;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
TransientDemo obj = new TransientDemo("張三", "123456");
File file = new File("obj.ser");
// 序列化
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(obj);
}
// 反序列化
TransientDemo restored;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
restored = (TransientDemo) ois.readObject();
}
System.out.println("name: " + restored.name); // null (被 transient 排除)
System.out.println("password: " + restored.password); // 123456 (保留)
}
}
若需 transient 字段也能序列化 (如加密存儲、衍生計算),可實現 writeObject/readObject:
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(encrypt(name)); // 手動寫入加密後的 name
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
this.name = decrypt((String) in.readObject()); // 手動讀取解密
}
logger, thread, socket)。Serializable,標記 transient 避免 NotSerializableException。@JsonIgnore, @XmlTransient)。readObject 中手動初始化。transient 是 Java 序列化的「開關」,用好它保護敏感信息、避免序列化失敗、優化傳輸體積。記住:**默認序列化只看非 transient 非 static 實例字段**。