关键字-transient

介绍

词义:短暂的
首先说说“序列化”,把一个对象的表示转化为字节流的过程称为串行化(也称为序列化,serialization),从字节流中把对象重建出来称为反串行化(也称为为反序列化,deserialization)。transient 为不应被串行化的数据提供了一个语言级的标记数据方法。

代码测试

1
public class TransientTest implements Serializable{
2
3
private static final long serialVersionUID = -2670851086407643335L;
4
5
private transient int a = 1; //不会被序列化(持久化),将该对象保存到磁盘中的时候,该属性不会被保存
6
7
private int b = 8;
8
9
public int getA() {
10
return a;
11
}
12
13
public int getB() {
14
return b;
15
}
16
}
17
18
//测试类
19
public class RunTest {
20
21
public static void main(String[] args) throws IOException, ClassNotFoundException {
22
//write Serializable object to file
23
TransientTest test = new TransientTest();
24
FileOutputStream fileOutputStream = new FileOutputStream("KeyWords/res/transienttest.txt");
25
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
26
objectOutputStream.writeObject(test);
27
objectOutputStream.flush();
28
objectOutputStream.close();
29
30
//get Serializable object from file
31
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("KeyWords/res/transienttest.txt"));
32
TransientTest transientTest = (TransientTest) objectInputStream.readObject();
33
System.out.println("a=" + transientTest.getA() + "\t" +"b=" + transientTest.getB());
34
}
35
36
}
Copied!

transienttest.txt文件内容

结果

如图