Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java transient

作者:放电的牛   发布日期:2025-08-17   浏览:17

import java.io.*;

class Employee implements Serializable {
    // 普通字段
    private String name;
    private int age;

    // 使用 transient 关键字修饰的字段,表示该字段不会被序列化
    private transient String password;

    // 构造函数
    public Employee(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }

    // 打印员工信息的方法
    public void printInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Password: " + (password == null ? "Not available" : password));
    }

    public static void main(String[] args) {
        // 创建一个 Employee 对象
        Employee emp = new Employee("Alice", 30, "secret");

        // 序列化对象到文件
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"))) {
            oos.writeObject(emp);
            System.out.println("Object has been serialized");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化对象从文件
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"))) {
            Employee deserializedEmp = (Employee) ois.readObject();
            System.out.println("Object has been deserialized");
            deserializedEmp.printInfo();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

解释说明

  1. transient 关键字:在 Java 中,transient 关键字用于修饰类的成员变量,表示该变量不会被序列化。当对象被序列化时,transient 变量的值不会被保存到磁盘或传输到其他地方。

  2. 序列化和反序列化

    • 序列化:将对象的状态保存到文件或其他存储介质中。
    • 反序列化:从文件或其他存储介质中恢复对象的状态。
  3. 示例代码中的 Employee

    • nameage 是普通的实例变量,会被序列化。
    • password 是用 transient 关键字修饰的变量,因此在序列化时不会被保存。
  4. 输出结果

    • 在反序列化后,password 的值会变成 null,因为它是 transient 的,没有被序列化保存。

通过这个例子可以清楚地看到 transient 关键字的作用。

上一篇:java contains

下一篇:java枚举

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站