Use the serialVersionUID or suppress warnings?

I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you.

Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where:

  • the form isn't compatible between different versions of your code.
  • you've suppressed the warning that this is the case.

Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it.


If you do not plan to serialize instances, add a SuppressWarning.

A generated serial ID can be a bit dangerous. It suggests that you intentionally gave it a serial number and that it is save to serialize and deserialize. It's easy to forget to update the serial number in a newer version of your application where your class is changed. Deserialization will fail if the class fields have been changed. Having a SuppressWarning at least tells the reader of your code that you did not intend to serialize this class.


I refuse to be terrorized by Eclipse into adding clutter to my code!

I just configure Eclipse to not generate warnings on missing serialVersionUID.


Thanks @ Steve Jessop for his answer on this. It was 5 lines of code... hardly a hassle.

I added @SuppressWarnings("serial") just above the class in question.

I also added this method:

private void writeObject(ObjectOutputStream oos) throws IOException {
   throw new IOException("This class is NOT serializable.");
}

Hopefully that's what Steve meant :)


Even if you know this object will be serialized there is no need to generate serialVersionUID because java will automatically generate it for you and will automatically keep track of changes so your serialization will always work just fine. You should generate it only if you know what you are doing (backward serialization compatibility, manual change tracking etc.)

So I would say suppressing the warning is the best and safest solution in most cases.