transient關鍵字詳解

作用:

  1. 一旦變量被transient修飾,變量將不再是對象持久化的一部分,該變量內容在序列化後無法獲得訪問。
  2. transient關鍵字只能修飾變量,而不能修飾方法和類。注意,本地變量是不能被transient關鍵字修飾的。變量如果是用戶自定義類變量,則該類需要實現Serializable接口。
  3. 一個靜態變量不管是否被transient修飾,均不能被序列化。

請看代碼:

//實體類(必須實現Serializable接口,才能被序列化)
public class Resume implements Serializable{
    private static final long serialVersionUID = 1L;
 
    private String name;
    private static String sex;
    transient private String age;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
 
    public String getAge() {
        return age;
    }
 
    public void setAge(String age) {
        this.age = age;
    }
 
    public void dispaly(){
        System.out.println("姓名:"+name+"\t年齡:"+age+"\t性別:"+sex);
    }
}
 
 
public class MainTest2 {
    public static void main(String[] args){
        try {
			// 序列化Resume
            Resume resume = new Resume();
            resume.setName("哈哈");
            resume.setSex("男");
            resume.setAge("20");
            resume.dispaly();
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("D:\\resume.txt"));
            outputStream.writeObject(resume);
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
 
 
    }
}

輸出結果:
姓名:哈哈 年齡:20 性別:男

反序列化:

public class MainTest2 {
    public static void main(String[] args){
        try {
            Resume resume = new Resume();
//            resume.setName("哈哈");
//            resume.setSex("男");
//            resume.setAge("20");
//            resume.dispaly();
//            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("D:\\resume.txt"));
//            outputStream.writeObject(resume);
//            outputStream.close();
 
            //改變sex(根據結果可見sex未被序列化,而是直接從內存中讀取)
            resume.setSex("女");
 
            //反序列化
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("D:\\resume.txt"));
            Resume resume1 = (Resume) inputStream.readObject();
            resume1.dispaly();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

輸出結果:
姓名:哈哈 年齡:null 性別:女

根據結果可知,age 字段被 transient 修飾未能序列化,而 sex 在反序列化之前改變了值,所以表明也未被序列化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章