Java: Should serializable inner & anonymous classes have SerialVersionUID?

给你一囗甜甜゛ 提交于 2020-01-21 05:20:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!