transient关键字

Java Transient Keyword

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

Let's take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age then we can declare the age data member as transient.

Example of Java Transient Keyword

In this example, we have created the two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.

If you deserialize the object, you will get the default value for transient variable.

Let's create a class with transient variable.

  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. }  

Now write the code to serialize the object.

  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.   
  11.   out.close();  
  12.   f.close();  
  13.   System.out.println("success");  
  14.  }  
  15. }  

Output:

success

Now write the code for deserialization.

  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. }  

转载于:https://my.oschina.net/u/3768168/blog/1615183

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值