File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About Object Serialization (Confusion)

 
gunjan bohra
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following code segment:

ObjectOutputStream out = new ObjectOutputStream(...);
MyObject obj = new MyObject(); //MyObject class is serializable
obj.setState(100);
out.writeObject(obj);
obj.setState(200);
out.writeObject(obj);

What is the final value of the field "state" in the serialized form?
It's an 100 then why?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It looks to me like you wrote 2 copies to out, the first with 100, the second with 200.
Bill
 
gunjan bohra
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya offcourse ..and when i got back .I will got the first one means 100
Why it's so ?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13045
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why it's so ?

I don't understand the source of your confusion. An ObjectOutputStream can be used to write one or many Serializable objects.
Bill
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Serialization doesn't write data, it writes objects. What gets written to your stream are two references to the same object. The second reference will not include the object's member data, because the serialization mechanism remembers which objects have already been written out, and by default won't write their data a second time, even if that data has changed.

If an object has already been written, and you want to write a second copy including the values of all the member variables as if the second copy were an altogether separate object, you have to call reset() on the ObjectOutputStream to tell it to forget about any previously-written objects.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic