设计抽象类时是否应该考虑序列化问题?

发布于 2024-12-18 05:57:50 字数 228 浏览 1 评论 0原文

一般来说,这个问题来自 Eclipse 建议在抽象类上添加串行版本 UID。

由于该类是抽象类,因此该类的实例永远不会存在,因此它们永远不会被序列化(只有派生类才会被序列化)。

所以我的问题是,在扩展器将被序列化的抽象类上放置 @SuppressWarnings("serial") 是否安全?

另外,在设计扩展器将被序列化的抽象类时需要注意的任何其他问题也是受欢迎的。

谢谢。

Generally this question comes from Eclipse suggesting to add a serial version UID on an abstract class.

Since the class is abstract instances of this class will never exist thus they will never be serialized (only derived classes will be).

So my question is it safe to place a @SuppressWarnings("serial") on an abstract class who's extenders will be serialized (and they will have serialVersionUIDs) ?

Also any other issues to be careful about when designing an abstract class who's extenders will be serialized are welcome.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

缺⑴份安定 2024-12-25 05:57:50

如果不是绝对需要(如果它没有状态),请不要使抽象类可序列化。您将需要终身维护类序列化形式,并为以前版本的序列化形式提供向后兼容性。但是您仍然需要提供一个无参数构造函数,以防扩展类自己实现 Serialized。

如果您决定实现 Serialized 接口,则需要抽象类上的串行版本 uid,否则当抽象类的新版本发布时,扩展类的序列化形式将被破坏。

Don't make the abstract class Serializable, if not absolutely needed (if it has no state). You will need to maintain the class serialized form for life and provide backwards compatibility for the previous versions of serialized forms. But you still need to provide a no parameter constructor in case the extending classes implements Serializable by themselves.

If you decide to implement the Serializable interface, you need the serial version uid on the abstract class, otherwise the serialized forms of extending classes will break when a new version of the abstract class is released.

尐偏执 2024-12-25 05:57:50

每个可序列化的类都需要一个serialVersionUID。如果一个对象属于本身扩展可序列化类的运行时类型,则涉及两个 serialVersionUID。所以,是的,您需要它,除非您决定不支持跨版本的序列化(如 Swing)。

Every serialisable class needs a serialVersionUID. If an object is of a runtime type that itself extends a serialisable class, then there are two serialVersionUIDs involved. So, yes you need it, unless you decide not to support serialisation across versions (like Swing).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文