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