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

相关推荐
论迹9 分钟前
【JavaEE】-- 多线程(初阶)2
java·开发语言·java-ee
桃子是唯一的水果18 分钟前
java 单例模式(Lazy Initialization)实现遍历文件夹下所有excel文件且返回其运行时间
java·单例模式·maven
+72019 分钟前
如何在java中用httpclient实现rpc post 请求
java·开发语言·rpc
ybq1951334543121 分钟前
javaEE-SpringBoot日志
java·spring boot·后端
火烧屁屁啦25 分钟前
【JavaEE进阶】图书管理系统 - 贰
java·spring
xzzd_jokelin25 分钟前
Spring AI 接入 DeepSeek:开启智能应用的新篇章
java·人工智能·spring·ai·大模型·rag·deepseek
刘什么洋啊Zz36 分钟前
剖析IO原理和零拷贝机制
java·运维·网络
卷心菜好6啊44 分钟前
特辣的海藻!2
java
心态与习惯1 小时前
mac 下 java 调用 gurobi 不能加载 jar
java·jar·mac·cplex·gurobi
he258191 小时前
centOS 7.9 安装JDK MYSQL
java·mysql·centos