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关键字只能修饰变量,而不能修饰方法和类,所以我们可以合理的使用该关键字

相关推荐
武子康1 小时前
Java-80 深入浅出 RPC Dubbo 动态服务降级:从雪崩防护到配置中心秒级生效
java·分布式·后端·spring·微服务·rpc·dubbo
舒一笑1 小时前
我的开源项目-PandaCoder迎来史诗级大更新啦
后端·程序员·intellij idea
灵感__idea2 小时前
JavaScript高级程序设计(第5版):好的编程就是掌控感
前端·javascript·程序员
YuTaoShao4 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
源码_V_saaskw4 小时前
JAVA图文短视频交友+自营商城系统源码支持小程序+Android+IOS+H5
java·微信小程序·小程序·uni-app·音视频·交友
超浪的晨4 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
双力臂4045 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试
Edingbrugh.南空5 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
QQ_4376643146 小时前
C++11 右值引用 Lambda 表达式
java·开发语言·c++
永卿0016 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式