Java Reference
In-Depth Information
FileUtil.printFileNotFoundMsg(fileObject.getPath());
}
catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
}
Name: John, Gender: Male, Height: NaN
Name: Wally, Gender: Male, Height: NaN
Name: Katrina, Gender: Female, Height: NaN
Objects were read from C:\book\javabook\personext.ser
For a Serializable object, the JVM serializes only instance variables that are not declared as transient . I will
discuss serializing transient variables in the next section. For an Externalizable object, you have full control over
what pieces of data are serialized.
Serialization of transient Fields
The keyword transient is used to declare a class's field. As the literal meaning of the word “transient” implies, a
transient field of a Serializable object is not serialized. The following code for an Employee class declares the ssn
and salary fields as transient :
public class Employee implements Serializable {
private String name;
private String gender;
private transient String ssn;
private transient double salary;
}
The transient fields of a Serializable object are not serialized when you use the writeObject() method of the
ObjectOutputStream class.
Note that if your object is Externalizable , not Serializable , declaring a field transient has no effect because
you control what fields are serialized in the writeExternal() method. If you want transient fields of your class to be
serialized, you need to declare the class Externalizable and write the transient fields to the output stream in the
writeExternal() method of your class. I will not cover any examples of serializing transient fields because the logic
will be the same as shown in Listing 7-26, except that you will declare some instance variables as transient and write
them to the output stream in the writeExternal() method.
Advanced Object Serialization
The following sections discuss advanced serialization techniques. They are designed for experienced developers.
If you are a beginner or an intermediate level developer, you may skip the following sections; you should, however,
revisit them after you gain more experience with Java I/O.
 
Search WWH ::




Custom Search