瞬态关键字transient

回顾static关键字

静态关键字static优先于非静态加载到内存当中(在使用的过程当中静态的东西优先于对象进入内存)
注意以下是新内容:
被static关键字修饰的成员变量不能被序列化,序列化的都是对象,如果被static修饰的话它不属于对象

举例示范

public class Person implements Serializable {
    String name = "张三";
    static int age = 18;
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}


public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\d.txt"));
        Object o = ois.readObject();
        ois.close();
        System.out.println(o);
    }

得到的结果如下
在这里插入图片描述

但是如果我们想某个成员变量不被显示出来的同时不让该变量被共享,那么我们引入了transient关键字

transient关键字:瞬态关键字

被该关键字修饰的成员变量不能被序列化

举例示范:

public class Person implements Serializable {
    static String name = "张三";

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                '}';
    }

    transient int age = 18;
}


public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\d.txt"));
        Object o = ois.readObject();
        ois.close();
        System.out.println(o);
    }

得到的结果为
在这里插入图片描述

posted @ 2020-11-05 16:00  谢海川  阅读(57)  评论(0)    收藏  举报