为什么Java有transient字段?
当您不想共享随序列化传递的某些敏感数据时,就需要它。
Thread
(感谢 @A.H. 的例子),在这种情况下,您可以将其标记为 transient。然而,线程本身并不是敏感数据,只是没有逻辑意义进行序列化(且它不能被序列化)。 - glen3btransient-keyword 的简化示例代码。
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);
}
}
Stream
对象。Connection
对象,因为它的状态也依赖于远程机器。简单来说,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;
}
}