Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use serialVersionUID

 
Jimmy Ho
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I'm doing some object serialization that will be passed between different JVMs on our networks here. I've been looking around, and I can't find basic information on what I'm supposed to add the serialVersionUID to.

Obviously, a class that implements Serializable that's going to be serialized is a candidate for adding an explicit serialVersionUID.

But what if I have the following structure? (from a Simple Factory Pattern implementation):
* interace A extends Serializable
* abstract class B implements A
* class C extends B

I know I should add a serialVersionUID to C, but what about interface A and abstract class B?
 
Jeff Storey
Ranch Hand
Posts: 230
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jimmy,

You don't need to add the serialVersionUID to the interface, but you should to both classes. According to the Java API documentions, "it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization." Another (not foolproof way, but useful) is to use an IDE like Eclipse and enable warnings for serializable classes that don't declare the serialVersionUID. It will tell you when you are missing it.

Jeff
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic