Below is a question from the Sybex
test bank on serialization.
import java.io.*;
public class AnimalCheckup {
private
String name;
private int age;
private static final ObjectStreamField[] ________________ =
{ new ObjectStreamField("name", String.class)};
private void writeObject(ObjectOutputStream stream)
throws Exception {
ObjectOutputStream.PutField fields = stream.putFields();
fields.put("name", name);
stream.writeFields();
}
private void readObject(ObjectInputStream stream)
throws Exception {
ObjectInputStream.GetField fields = stream.readFields();
name = (String) fields.get("name", null);
}
}
A. Serializable
B. Serialized
C. serialFields
D. serialPersistentFields
E. transient
F. None of the above
This is the answer:
When implementing serialization, there are two main ways for omitting an instance variable. Option E is tricky because transient is one of those ways. However, it is incorrect because it must be used on the instance variable to be omitted. Option D is correct because it is the other way. The serialPersistentFields array lists the fields available to writeObject() and readObject().
However since the class does not implement Serializable, how would adding a serialPersistentFields make any difference? An exception would be thrown when an object of that class is being serialized.