1

Can someone tell me how serialization work for an object. I tried googling but for so reason I always get lost in details. I just need to know when you serialize an object whose class has private/public variables, static variables and private/public methods. Does everything get serialized or just the variables? Like is it a bad habit to have an object with many methods who will be serialized to be passed across activities?

asteri
  • 11,402
  • 13
  • 60
  • 84
Snake
  • 14,228
  • 27
  • 117
  • 250
  • 1
    Maybe [this article](http://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html) will help. Also [here](http://stackoverflow.com/questions/14730150/how-does-java-serialise-the-implementationsof-methods-within-an-object/14730752#14730752) you have similar question. – Pshemo Feb 11 '13 at 18:17

1 Answers1

4

Only the state of the object is serialized - the fields, in other words. The methods themselves are not serialized. However, the generated version number is also effectively part of the state, and that depends on what methods are present. You can change this behaviour with a serialVersionUid field, admittedly - but it's still tricky.

Personally I'd strongly recommend against using Java binary serialization - it ends up being really quite tricky to manage backward and forward compatilility. There are plenty of other serialization frameworks available, which usually require a bit more work to get started with than Java serialization, but end up being more portable and maintainable. Personally I'm a fan of Protocol Buffers but I'm biased :)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you , make sense. I just wanted to ensure that, while using serialVersionUid, if I add 30 methods to class it won't make serialization complicated or time consuming – Snake Feb 11 '13 at 18:58
  • @Snake: It won't change the stored data, no. – Jon Skeet Feb 11 '13 at 19:18