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

相关推荐
木井巳5 小时前
【递归算法】目标和
java·算法·leetcode·决策树·深度优先
亦暖筑序5 小时前
手写 Spring AI Agent:让大模型自主规划任务,ReAct 模式全流程拆解
java·人工智能·spring
敖正炀5 小时前
ReentrantLock 与 synchronized对比
java
程序员鱼皮5 小时前
SBTI 爆火后,我做了个程序员版的 CBTI。。已开源 + 附开发过程
ai·程序员·开源·编程·ai编程
XiYang-DING5 小时前
【Java】二叉搜索树(BST)
java·开发语言·python
weixin_437957615 小时前
Mysql安装不成功
java
Lyyaoo.5 小时前
【JAVA基础面经】进程安全问题(synchronized and volatile)
java·开发语言·jvm
Andya_net5 小时前
Java | 基于 Feign 流式传输操作SFTP文件传输
java·开发语言·spring boot
_Evan_Yao5 小时前
别让“规范”困住你:前后端交互中的方法选择与认知突围
java·后端·交互·restful
星乐a6 小时前
String vs StringBuilder vs StringBuffer深度解析
java