4

Although I'm not currently planning to serialize anything, I give all serializable outer classes, as well as static nested classes a SerialVersionUID, because that is the proper way to do it.

However, I've read here that

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged for several reasons. ...

So my question is:

Should I give inner and anonymous classes a SerialVersionUID each, or should I add a @SuppressWarnings("serial") to those?

Is one way more proper than the other?

I will in any case make references to such classes transient, because I don't want them to be serialized.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Lone nebula
  • 4,768
  • 2
  • 16
  • 16
  • I think the advice that you should not serialize theses classes is discouraged because you don't know wheter the JVM, that deserializes the objects has the classes on the classpath. – keuleJ Mar 18 '13 at 12:47
  • So I should treat them as other serializable classes? – Lone nebula Mar 18 '13 at 13:00
  • I would only use a serialVersionUID, if you need compatiblity between versions. eg. if you write the objects in a file or similar. – keuleJ Mar 18 '13 at 13:27
  • Regarding anonymous classes in particular: I've noticed that recent versions of opensdk have stopped warning about these. (I have opensdk8 and opensdk11; the former warns and the latter doesn't.) Not sure about other inner classes; I find it difficult to tell how the compiler decides whether to warn or not. – Don Hatch Aug 23 '20 at 13:53

1 Answers1

4

Give them a serialVersionUID, because:

  • It's good general practice and it certainly doesn't hurt to specify it.
  • Warnings should be addressed, not suppressed.
  • Sometimes inner classes are changed to be top-level classes when they get large enough.

It's good (for all of the reasons stated in the documentation to which you've linked) that you won't be serializing instances of those inner classes. I suppose, if you were paranoid or worried other developers might not exercise the same good judgement, you could enforce that choice by having a writeObject method in each inner class that unconditionally throws an exception.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • I guess I won't go as far as to add writeObject methods to each inner class. Especially since some (mainly anonymous classes) are intended to be as short as possible, for more tidiness. But I'll add a SerialVersionUID at least. – Lone nebula Mar 18 '13 at 13:27
  • @Lonenebula You don't usually need to add `writeObject()` etc methods unless you already have a serialization problem. – user207421 Mar 19 '13 at 04:33