Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Serialization

 
Harry Tuttle
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I'm just reading the serialization in the SCJP-Book 6.0 and how to use writeObject and readObject if an object is not serializable but used in a composition at page 465. suppose the not serializable object has a juge of member variables. if i got the idea in the book i have to write them all manually and read them one by one and assign them to the not serializable object. is that right?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No ...

you have a defaultWriteObject and defaultReadObject method which you want to use if you need to serialize the state of transient variables (if any library you use has classes that don't implement serializable) or if you changed your class and need to do adaptions to the read process of the objects.
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian, I think Harry is right. defaultReadObject and defaultWriteObject are used to read/write the non-transient fields. In this case, the non-serializable fields should be made transient. writeObject must then write their fields one by one manually, and readObject must recreate the non-serializable fields and then read their fields one by one manually (or vice versa if you need the fields in constructors). This does mean that these non-serializable fields cannot be final.

You may be able to automate things by using reflection, but be aware that this may (will?) cause problems if you add, remove or change fields.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic