Java 关键字【transient】作用!

transient

在Java中,transient 是一个关键字,用于声明一个字段不会被序列化。
当一个对象被序列化时,被声明为 transient 的字段将不会被保存到序列化的结果中

主要用途:

  • 敏感信息隐藏: transient 可以用于隐藏对象中的敏感信息,确保它们不会被持久化到存储设备或通过网络传输
  • 临时数据: 有些字段在持久化时不需要被保存,比如缓存或临时计算的数据

注意事项:

  • transient 只能用于字段,不能用于类或方法
  • 被声明为 transient 的字段在反序列化时会被设置为默认值,如 null(对于对象)、0(对于基本数据类型)或 false(对于布尔类型)
  • 序列化过程中,transient 字段的内容不会被保存到序列化结果中
  • transient 只影响对象的序列化,不影响其它方面的行为,比如字段的访问权限等

示例


import java.io.*;

class Person implements Serializable {
    private String name;
    private transient String password; // 密码字段被声明为 transient

    public Person(String name, String password) {
        this.name = name;
        this.password = password;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public String getPassword() {
        return password;
    }

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

public class TransientExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Person person = new Person("Alice", "123456");

        // 序列化对象
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"));
        out.writeObject(person);
        out.close();

        // 反序列化对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"));
        Person deserializedPerson = (Person) in.readObject();
        in.close();

        // 输出反序列化后的对象
        System.out.println("姓名:" + deserializedPerson.getName());
        System.out.println("密码:" + deserializedPerson.getPassword()); // 密码字段为 null
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值