zoukankan      html  css  js  c++  java
  • 关于Java中的transient关键字

    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.

  • 相关阅读:
    最短路算法模板SPFA、disjkstra、Floyd
    数组排序
    java数组之二分法查找
    笔算开平方-20171211
    JSP+Servlet+DAO+Javabean模式小记-20171029
    java中创建List<>类型的数组-20171028
    Android及java中list循环添加时覆盖的问题-20171021
    Java-20180412
    centos 7.2 安装gitlab汉化
    docker 容器配置tocmat时间不统一
  • 原文地址:https://www.cnblogs.com/HarrisonHao/p/6106758.html
Copyright © 2011-2022 走看看