Skip to content
Rain Hu's Workspace
Go back

[Java] transient 關鍵字

Rain Hu

1. transient 的作用及使用方法

注意讀取時,讀取數據的順序一定要和存放數據的順序保持一致。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TransientExample {
    public static void main(String[] args){
        User user = new User();
        user.setUsername("Rain");
        user.setPassword("12345678");

        System.out.println("Read before Serializable: ");
        System.out.println("Username: " + user.getUsername());
        System.out.println("Password: " + user.getPassword());

        try {
            ObjectOutput os = new ObjectOutputStream(new FileOutputStream("/Users/rainhu/workspace/algo/temp/user.txt"));
            os.writeObject(user);
            os.flush();
            os.close();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream("/Users/rainhu/workspace/algo/temp/user.txt"));
            user = (User) is.readObject();
            is.close();

            System.out.println("Read after Serializable: ");
            System.out.println("Username: " + user.getUsername());
            System.out.println("Password: " + user.getPassword());
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }
}

class User implements Serializable{
    private static final long serialVersionID = 8294180014912103005L;
    
    private String username;
    private transient String password;

    public String getUsername(){
        return username;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public String getPassword(){
        return password;
    }
    
    public void setPassword(String password){
        this.password = password;
    }
}

Read before Serializable:
Username: Rain
Password: 12345678
Read after Serializable:
Username: Rain
Password: null

2. transient 的小結

  1. 一旦變數被 transient 修飾,變數將不再是物件持久化的一部分,該變敗內容將在序列化後無法再次訪問。
  2. transient 關鍵字只能飾飾變數(variable),不能修飾方法(method)和類別(class)。注意,區域變數是無法被 transient 修飾的。
  3. 被 transient 修飾的變數不能再被序列化,一個靜態變數不管是否被 transient 修飾,都不能被序列化。

3. 當遇上了 Externalizable


Share this post on:

Previous
[CS50] Lec 1 - C
Next
[Device] Mismatch Introduction