For class that implements Serializable
interface there are 2 ways to define what specific fields get streamed during the serialization:
Serializable
are preserved. ObjectStreamField [] serialPersistentFields
and explicitly declaring the specific fields saved. I wonder, what is the advantage of the second method except for the ability to define specific fields order?
Luckily, I'm actually writing this up right now.... Besides the advantages mentioned (and I don't know much about unshared), writing your own output format seems to have the following advantages:
I've seen the documentation you're quoting, and mentioning just those 2 options is a bit misleading and leaves quite a bit out: you can customize your serialization format in 2 ways, by using the ObjectOutput/InputStream interface to write and read fields in a particular order (described in Bloch), and using the PutField and GetField classes to write and read fields by name. You can use serialPersistentFields as your quote mentions to extend this second method, but it's not required unless you need to read or write data with a name which is not a member variable name.
There's a 3rd way to control format as well, using the Externizable interface, though I haven't explored that much. And some of the advantages can also be gotten through Serialization Proxies (see Bloch).
Anyone feel free to correct me on details if I missed anything.
The 'advantage' is that it does what it says in the Javadoc: defines which fields are serialized. Without it, all non-transient non-static fields are serialized. Your choice.
The advantage is you can conditionally populate ObjectStreamField at runtime albeit only once per JVM lifecycle to determine which fields should be serialized.
private static final ObjectStreamField [] osf;
static {
//code to init osf
}
In serialPersistentFields
you can specify fields that are not necessarily present in the class anymore.
See for example the jdk class java.math.BigInteger
, where several fields are read and written which don't exist anymore in the class. These obsolete fields are still read and written for compatibility with older versions. The reading and writing of these fields is handled by the readObject()
and writeObject()
methods.
See also http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serial-arch.html#6250
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.