问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/15477169/java-should-serializable-inner-anonymous-classes-have-serialversionuid