Java中的transient关键字是在序列化时候用的,如果用transient修饰变量,那么该变量不会被序列化。
下面的例子中创建了一个Student类,有三个成员变量:id,name,age。age字段被transient修饰,当该类被序列化的时候,age字段将不被序列化。
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}
来创建一个用序列化的类:
import java.io.*;
class PersistExample{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi",22);//creating object
//writing object into file
FileOutputStream f=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(f);
out.writeObject(s1);
out.flush();
out.close();
f.close();
System.out.println("success");
}
}
Output: success
再来创建一个反序列化的类:
import java.io.*;
class DePersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
in.close();
}
}
Output:211 ravi 0
由此可见,Student的age字段并未被序列化,其值为int类型的默认值:0.