用java这么久居然都不知道这个关键字,最近在读effective_java时才发现了,,于是去看了看这个关键字
transient,汉语意思短暂的,瞬态.这个关键字在java中的作用就是用它修饰的字段在被反序列化时会被忽略掉,什么意思呢。。我们来看看:
public class Student implements Serializable {
private String name;
// transient修饰了age字段
private transient Integer age;
...
}
因为Student类的age字段是被transient修饰的,所以我们来看一段代码的结果:
Student student = new Student();
student.setAge(12);
student.setName("sam");
System.out.println(student);
// 序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("s.out"));
oos.writeObject(student);
oos.close();
// 反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("s.out"));
Object o = ois.readObject();
ois.close();
System.out.println(o);
try,catch的为了简便就省略了,结果:
可以看到,在反序列化后,age变成了null,这就是transient关键字的作用