This page looks best with JavaScript enabled

transient关键字

 ·  ☕ 1 min read

transient 关键字

transient关键字声明的成员变量,在序列化时会被忽略。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public abstract class Main {
    public static void main(String[] args) {
        User user = new User("name", "pwd");
        try (ObjectOutputStream oop = new ObjectOutputStream(new FileOutputStream("user.txt"))) {
            oop.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        User readUser = null;
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.txt"))) {
            readUser = (User) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (readUser != null) {
            System.out.println(readUser);         
        }
    }

}

class User implements Serializable {
    String name;
    transient String pwd;

    public User(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

输出:

1
User{name='name', pwd='null'}
Support the author with
alipay QR Code
wechat QR Code

Yang
WRITTEN BY
Yang
Developer