transient关键字使用

前言

在Java操作对象中,如果我们不想将对象中的字段序列化到网络传输,可以使用transient修饰成员变量

transient使用例子

例如在读写文件流中,如果对象不用transient修饰的话

java 复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Example implements Serializable {

    private Long id;

    private String name;

    private int age;

    public static void main(String[] args) {
        Example example = new Example(1L, "aa", 20);
        File file = new File("d:/1.txt");
        try (ObjectOutputStream fileOutputStream = new ObjectOutputStream(new FileOutputStream(file));
             ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
            fileOutputStream.writeObject(example);
            Example example1 = (Example) objectInputStream.readObject();
            System.out.println(example1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

输出结果为

对象使用transient修饰的话

java 复制代码
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Example implements Serializable {

    private Long id;

    private String name;

    private transient int age;

    public static void main(String[] args) {
        Example example = new Example(1L, "aa", 20);
        File file = new File("d:/1.txt");
        try (ObjectOutputStream fileOutputStream = new ObjectOutputStream(new FileOutputStream(file));
             ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
            fileOutputStream.writeObject(example);
            Example example1 = (Example) objectInputStream.readObject();
            System.out.println(example1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}

输出结果为

json操作也一样

typescript 复制代码
public class JsonDemo {

    public static void main(String[] args) {
        Example example = new Example(1L, "aa", 20);
        System.out.println(JSON.toJSONString(example));
    }
}

输出结果为

总结

一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法被访问,并且transient关键字只能修饰变量,而不能修饰方法和类,所以我们可以合理的使用该关键字

相关推荐
小七在进步6 分钟前
C++入门(2)
java·jvm·c++
To0R11 分钟前
Agent 上线前必须过的五道门(附 Spring Boot 实现)
java
vipxieliang19 分钟前
固定电话验证详解:区号、号码、分机号的完整验证
java·spring boot
步行cgn26 分钟前
Spring Boot 主入口类上的 @Enable 和 @Scan 注解详解
java·spring boot·后端
lhldsg27 分钟前
全民健身解决方案软件开发实战:从架构设计到部署指南
java·前端·数据库·小程序
两点王爷29 分钟前
Java 与前端加载 MVT 数据:从服务端切片到浏览器渲染
java·前端·状态模式
TinyMemory1 小时前
Java 面向对象核心入门(九):方法重写 Override|彻底分清重载与重写
java·面向对象·override·方法重写·重载与重写
程序员cxuan1 小时前
GPT images 2.5 一手实测,这也太颠了。。。
后端·程序员
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-09-08
java·ide·深度学习·百度·intellij-idea
IT枫斗者枫哥1 小时前
Java 文件导出:写完了,为什么还不能标记成功?
java