0

We can serialize an object by implementing Serializable interface. Then when should we go for custom Serialization by providing below to methods and Why should we called defaultWriteObject and defaultReadObject methods?

private void writeObject(ObjectOutputStream out) throws IOException 
{           out.defaultWriteObject(); 

}

private void readObject(ObjectInputStream in) throws  IOException, ClassNotFoundException 
{           
   in.defaultReadObject();

}     
Rajanikanta Pradhan
  • 580
  • 1
  • 8
  • 12
  • Maybe this will [help](https://stackoverflow.com/questions/7290777/java-custom-serialization) – Parag Jadhav Sep 21 '17 at 07:05
  • Possible duplicate of [Java Custom Serialization](https://stackoverflow.com/questions/7290777/java-custom-serialization) – Shubhendu Pramanik Sep 21 '17 at 07:12
  • I go through that post but did not get it, Can you please explain . Subhendu – Rajanikanta Pradhan Sep 21 '17 at 07:18
  • @RajanikantaPradhan When you customize your serialization through `writeObject` method it's completely upto the developer how he wants to serialize the object. That's why you call this `defaultWriteObject` method inside `writeObject` method. What this method does is include the allowed members to the stream for serialization i.e. non-static and transient fields. [Refer] (https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#defaultWriteObject()) – Shubhendu Pramanik Sep 21 '17 at 07:38
  • @ShubhenduPramanik You mean non-static, *non*-transient fields, i.e fields which are both, not both sets of fields. – user207421 Sep 21 '17 at 08:06
  • `static int a;` //not allowed `transient int b;` //not allowed `int c;` //allowed `static transient int d;` //not allowed @EJP Hope clear now – Shubhendu Pramanik Sep 21 '17 at 09:27

1 Answers1

1

There could be various reasons, it's one of the many things you only rant find out about when you are trying to solve a problem.

You could be wanting to serialise some third party type objects which are not serializable. Or on read you could be migrating data from a deprecated field into another location, avoiding the need to run a large scale migration.

I am sure that there are many other reasons, I just have not had to solve those problems yet.

The default read and write methods basically default serialisation happens, and your code is just additional, so be aware the order you call that and your custom code.

MartinByers
  • 1,240
  • 1
  • 9
  • 15