This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Back from a long weekend with a new question for you.
Q. Do we have control on the process of de-serialization? Suppose I have a class that has 2 instance variables, out of two one is declared transient - so this variable don't take part in the process of serialization, now I serialize an instance of this class and then de-serialize the stream I got from serialization, so the transient variable will be null in the object we got from de-serialization (Right?), now can I control this process? Can I have something else than null in transient variable?
Ankur, A suggestion...Instead of starting a separate thread for each question it would be better if you can continue posting the question in the same thread,else it would clutter the Jobs Discussion board and make it look like a technical forum...
Just my 2 cents... [ April 08, 2008: Message edited by: Rambo Prasad ]
Helping hands are much better than the praying lips
With the readResolve, readObject and writeObject methods you can have a quite extensive control over serialization and deserialization.
A little explanation on each:
readResolve can be used to return the same static instance for singletons. If present, this method is used to determine the result of deserialization. Example:
Without the readResolve method, you can actually duplicate the Singleton object by serializing and deserializing it. Because the readResolve method returns INSTANCE, it will not duplicate it but return the one single instance.
Now you won't use this method much, unlike readObject and writeObject. These are mostly used to perform some extra steps when (de)serializing. They usually start with "in.defaultReadObject()" for readObject and "out.defaultWriteObject()" for writeObject. The (de)serialize the non-transient fields as usual. If you omit them nothing will be (de)serialized. What follows next is up to the programmer, but readObject usually (re)initializes transient values.
One note: these methods can be (and should be!) kept private, as the JVM will use reflection to call them. Don't worry about how at the moment, just that it works. [ April 08, 2008: Message edited by: Rob Prime ]