掘金 后端 ( ) • 2024-04-13 16:16

前言

在Java操作对象中,如果我们不想将对象中的字段序列化到网络传输,可以使用transient修饰成员变量

transient使用例子

例如在读写文件流中,如果对象不用transient修饰的话

@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();
        }

    }


}

输出结果为

image.png 对象使用transient修饰的话

@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();
        }

    }


}

输出结果为

image.png json操作也一样

public class JsonDemo {

    public static void main(String[] args) {
        Example example = new Example(1L, "aa", 20);
        System.out.println(JSON.toJSONString(example));
    }
}

输出结果为

image.png

总结

一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法被访问,并且transient关键字只能修饰变量,而不能修饰方法和类,所以我们可以合理的使用该关键字