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

相关推荐
老华带你飞3 分钟前
医院挂号|基于Java医院挂号管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
豐儀麟阁贵7 分钟前
9.6使用正则表达式
java·开发语言·数据库·mysql
杀死那个蝈坦20 分钟前
Docker
java·docker·eclipse·tomcat·hibernate
a31582380621 分钟前
Android13隐藏某个App需要关注的源码文件
android·java·framework·launcher3·隐藏app
悟空码字28 分钟前
SpringBoot实现消息推送:让服务器学会“主动搭讪”
java·spring boot·后端
蒟蒻小袁34 分钟前
Hot100--找到字符串中所有字母异位词
java·算法·leetcode·面试
+VX:Fegn089544 分钟前
人力资源管理|基于springboot + vue人力资源管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
即随本心0.o1 小时前
SSE服务搭建
java·spring boot
MarkHD1 小时前
车辆TBOX科普 第56次 从模块拼接到可靠交付的实战指南
java·开发语言