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

java中transient关键字的作用

作者:岁月凉茶   发布日期:2025-12-05   浏览:32

import java.io.*;

class Employee implements Serializable {
    public String name;
    public transient int id; // 使用transient关键字标记id字段

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return "Employee{name='" + name + "', id=" + id + "}";
    }

    public static void main(String[] args) {
        Employee e = new Employee("John Doe", 12345);

        try {
            // 序列化对象
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();

            // 反序列化对象
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Employee e2 = (Employee) in.readObject();
            in.close();
            fileIn.close();

            System.out.println("Deserialized Employee: " + e2);
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

解释说明:

  • transient 关键字用于标记那些在序列化过程中不需要保存的成员变量。
  • 在上面的代码中,id 字段被标记为 transient,因此在序列化时不会被保存到文件中。当反序列化时,id 的值会恢复为默认值(对于 int 类型,默认值是 0)。
  • 运行该程序后,你会看到反序列化后的 Employee 对象中 id 的值为 0,而 name 仍然保留了原来的值。

上一篇:java 异或

下一篇:java post

大家都在看

java判断是windows还是linux

java连接数据库的代码

java djl

ubuntu 卸载java

es java api

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

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

Laravel 中文站