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

相关推荐
2401_837088501 小时前
stringRedisTemplate.opsForHash().entries
java·redis
lkbhua莱克瓦242 小时前
Java基础——集合进阶3
java·开发语言·笔记
蓝-萧3 小时前
使用Docker构建Node.js应用的详细指南
java·后端
多喝开水少熬夜3 小时前
Trie树相关算法题java实现
java·开发语言·算法
lkbhua莱克瓦244 小时前
Java基础——集合进阶用到的数据结构知识点1
java·数据结构·笔记·github
mapbar_front4 小时前
进入职场第二课—融入
程序员
音符犹如代码4 小时前
Java并发List实战:CopyOnWriteArrayList原理与ArrayList常见面试题
java·开发语言·面试·list
代码or搬砖5 小时前
Docker 部署 Java 项目实践
java·docker·容器
又是忙碌的一天5 小时前
抽象类和接口
java·开发语言
August_._5 小时前
【MySQL】SQL语法详细总结
java·数据库·后端·sql·mysql·oracle