为什么Java有瞬时字段?


当前回答

允许您定义不希望序列化的变量。

在对象中,您可能有不希望序列化/持久化的信息(可能是对父工厂对象的引用),或者序列化没有意义。将这些标记为“瞬时”意味着序列化机制将忽略这些字段。

其他回答

允许您定义不希望序列化的变量。

在对象中,您可能有不希望序列化/持久化的信息(可能是对父工厂对象的引用),或者序列化没有意义。将这些标记为“瞬时”意味着序列化机制将忽略这些字段。

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

简单地说,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;

   }
}

瞬态变量是在类序列化时不包含的变量。

我想到的一个可能有用的例子是,只有在特定对象实例的上下文中才有意义的变量,并且在序列化和反序列化对象之后,这些变量就会变得无效。在这种情况下,让这些变量变为空是很有用的,这样您就可以在需要时用有用的数据重新初始化它们。

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

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