transient是在***序列化***中的变量修饰符,当序列化时,如果不想保存一个变量的值到文件中,可以使用transient关键字。当JVM遇到transient关键字,会忽略这个变量原始值,会保存这个变量数据类型的默认值。
transient在安全约束上非常重要,例如,不想在文件中保留私密数据。另一个情况是不保留由其他序列化变量计算所得的变量值,例如,年龄,当前日期等。
实际上,仅仅序列化表示实例状态的变量,当在序列化时,要在私密变量前加transient。
// 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
}
transient和static:因为static变量并不是表示实例状态,当static与transient结合修饰变量时,会序列化该变量,但是并不报错。
transient和final:final变量的值是直接被序列化,当final与transient结合修饰变量时,会序列化该变量,但是并不会报错。
// 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);
}
}
输出结果为:
i = 10
j = 20
k = 0
l = 40
m = 50