一 无聊的简介

In computer programming, transient is a property of any element in the system that is temporary. The term applies to transient applications, i.e. software for the end-user which is displayed with a transient application posture; transient data, which is discarded after it is no longer needed by the computation; and transient code which are subroutines or software components that are loaded in the system only for a fraction of the total run time.

Examples of applications of the term are described below.

– 以上内容来自: wiki

二 代码示例

  • Person.java

    import java.io.Serializable;
    
    public class Person implements Serializable {
        public static final long serialVersionUID = 42L;
    
    
        public String name = "zhangsan";
        public Integer age = 16;
        //
        transient String unserializedVariables = "Will not be serialized here";
    
        transient final String finalUnserializedVariables = "Don't want to ignore me";
    }
    
  • Main.java

    public static void main(String[] args) {
            Person person = new Person();
            // 然后把他存入一个 txt中
            try {
                // 序列化
                try (FileOutputStream fileOutputStream = new FileOutputStream("a.txt")) {
                    try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) {
                        objectOutputStream.writeObject(person);
                    }
                }
    
                // 反序列化
                try (FileInputStream fileInputStream = new FileInputStream("a.txt")) {
                    try (ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
                        Person p = (Person) objectInputStream.readObject();
                        System.out.println(p.age); // 18
                        System.out.println(p.name); // zhangsan
                        System.out.println(p.unserializedVariables); // null
                        System.out.println(p.finalUnserializedVariables); // Don't want to ignore me
                    }
                }
    
            } catch (IOException | ClassNotFoundException e) {
                e.fillInStackTrace();
            }
    
        }
    

由上面可以看到 System.out.println(p.unserializedVariables); 这个返回的值为 null 。这是因为我在 Person.javaunserializedVariables 变量前添加了 transient

transient 是序列化中使用的变量修饰符。在序列化的时候,如果我们不想在文件中保存某个特定变量的值,那么我们使用 transient 关键字。当 JVM 遇到 transient 关键字时,它会忽略变量的原始值并保存该变量数据类型的默认值。

其中还有一个变量我也加了 transient 关键字 transient final String finalUnserializedVariables 但是当关键字 transient 遇到 final 的时候 就会失效

final变量直接按它们的值序列化,因此将 final 变量声明为 transient 没有任何用途/影响。但是并没有编译时错误。