为什么Java有瞬时字段?


当前回答

使用瞬时修饰符声明的字段将不会参与序列化过程。当对象被序列化(以任何状态保存)时,其瞬态字段的值在串行表示中被忽略,而瞬态字段以外的字段将参与序列化过程。这是transient关键字的主要目的。

其他回答

简单地说,transient java关键字保护字段不被序列化为其非transient字段计数器部分。

在这个代码片段中,我们的抽象类BaseJob实现了Serializable接口,我们从BaseJob扩展,但不需要序列化远程和本地数据源;仅序列化organizationName和isSynced字段。

public abstract class BaseJob implements Serializable{
   public void ShouldRetryRun(){}
}

public class SyncOrganizationJob extends BaseJob {

   public String organizationName;
   public Boolean isSynced

   @Inject transient RemoteDataSource remoteDataSource;
   @Inject transient LocalDaoSource localDataSource;

   public SyncOrganizationJob(String organizationName) {
     super(new 
         Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());

      this.organizationName = organizationName;
      this.isSynced=isSynced;

   }
}

使用瞬时修饰符声明的字段将不会参与序列化过程。当对象被序列化(以任何状态保存)时,其瞬态字段的值在串行表示中被忽略,而瞬态字段以外的字段将参与序列化过程。这是transient关键字的主要目的。

因为并非所有变量都具有可序列化的性质

当您不想共享一些与序列化相关的敏感数据时,需要使用它。

瞬时关键字的简化示例代码。

import java.io.*;

class NameStore implements Serializable {
    private String firstName, lastName;
    private transient String fullName;

    public NameStore (String fName, String lName){
        this.firstName = fName;
        this.lastName = lName;
        buildFullName();
    }

    private void buildFullName() {
        // assume building fullName is compuational/memory intensive!
        this.fullName = this.firstName + " " + this.lastName;
    }

    public String toString(){
        return "First Name : " + this.firstName
            + "\nLast Name : " + this.lastName
            + "\nFull Name : " + this.fullName;
    }

    private void readObject(ObjectInputStream inputStream)
            throws IOException, ClassNotFoundException
    {
        inputStream.defaultReadObject();
        buildFullName();
    }
}

public class TransientExample{
    public static void main(String args[]) throws Exception {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("ns"));
        o.writeObject(new NameStore("Steve", "Jobs"));
        o.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("ns"));
        NameStore ns = (NameStore)in.readObject();
        System.out.println(ns);
    }
}