Reputation: 8473
Under what circumstances and for what reasons should one consider customizing the serialization
process? (The following methods are the methods that will be invoked by the JVM
)
private void writeObject(java.io.ObjectOutputStream out){
//customize serialization
}
private void readObject(java.io.ObjectInputStream in){
//customize de-serialization
}
Upvotes: 2
Views: 225
Reputation: 124295
One of advantages of customized serialization is possibility to add transient fields (like inherited from other classes) into serialization process. You can do it like this
class NotMyClass implements Serializable {
String login;
transient String password;
//...
}
//I want to serialize also transient password field
class MyClass extends NotMyClass {
private void writeObject(ObjectOutputStream out) throws IOException {
System.out.println("defaul serialization");
out.defaultWriteObject();
System.out.println("my serialization >>>> adding inherited transient value");
out.writeObject(password);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
System.out.println("defaul deserialization");
in.defaultReadObject();
System.out.println("my deserialization <<<< reading stored transient value");
password = (String) in.readObject();
}
}
Upvotes: 1
Reputation: 13374
One other great reason is when you want to reduce the amount of data getting serialized. Take for example a HashMap
with a capacity of say 1024. Let's say it has just 3 entries so far. Serializing an Object
array of 1024 would be very wasteful, when all it needs to do is serialize the three entries.
On a separate note, if the objects you are serializing have references to non-serializable services, you would first mark those members as transient (to prevent serialization), but then use the writeObject
to capture enough information so that readObject
can re-establish the references upon de-serialization.
Upvotes: 0
Reputation: 4704
I'm thinking some cases where you may want to control the serialization:
Those are the reasons I can think of right now.
Hope it helps.
Upvotes: 2
Reputation: 38571
Read Advanced Serialization from SUN
readObject
and writeObject
is to serialize the data for a superclass that is not Serializable
itself.Upvotes: 2
Reputation: 597
You might want to customize what you want to do at the time of a read or write-- you can add extra logging, you can perform computations, you might only want to read or write if certain conditions are met, etc. Really, you can do anything Java allows. For an example, see the section "Customize the Default Protocol" at http://java.sun.com/developer/technicalArticles/Programming/serialization/
Upvotes: 0
Reputation: 8473
The only reason I can think of is when you want your sub-class to void serialization
while the super-class is already serializable
, and then you can just simply throw exception there in both methods in your sub-class.
I am not sure if there's any other specific reason or not.
Upvotes: 0