English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java中为什么没有序列化瞬时变量?

序列化是以字节序列的形式持久化Java对象的过程,该字节序列包括对象的数据以及关于对象的类型和存储在对象中的数据类型的信息。 序列化是将Java对象的值/状态转换为字节,以便通过网络发送或保存。 另一方面,反序列化是将字节码转换为相应的Java对象。

瞬时变量是其值在序列化过程中未序列化的变量。 当我们反序列化该变量时,我们将获得该变量的默认值。

语法

private transient <member-variable>;

示例

import java.io.*;
class EmpInfo implements Serializable {
   String name;
   private transient int age;
   String occupation;
   public EmpInfo(String name, int age, String occupation) {
      this.name = name;
      this.age = age;
      this.occupation = occupation;
   }
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.app*end("Name:"+"\n");
      sb.append(this.name+"\n");
      sb.append("Age:"+ "\n");
      sb.append(this.age + "\n");
      sb.append("Occupation:" + "\n");
      sb.append(this.occupation);
      return sb.toString();
   }
}
// main class
public class TransientVarTest {
   public static void main(String args[]) throws Exception {
      EmpInfo empInfo = new EmpInfo("Adithya", 30, "Java Developer");
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("empInfo"));
      oos.writeObject(empInfo);
      oos.close();
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("empInfo"));
      EmpInfo empInfo1 = (EmpInfo)ois.readObject();
      System.out.println(empInfo1);
   }
}

输出结果

Name:
AdithyaAge:
0Occupation:
Java Developer