Java:应该是可序列化的内部和外部匿名类有Seri​​alVersionUID吗? [英] Java: Should serializable inner & anonymous classes have SerialVersionUID?

查看:187
本文介绍了Java:应该是可序列化的内部和外部匿名类有Seri​​alVersionUID吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我目前不打算序列化任何东西,但我给所有可序列化的外部类,以及静态嵌套类a SerialVersionUID ,因为这是正确的方法这样做。

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.

但是,我读过这里


内部类的序列化(即嵌套类)这些不是静态成员类,包括本地和匿名类,强烈建议不要出于几个原因。 ...

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. ...

所以我的问题是:

我应该给内心和匿名类每个 SerialVersionUID ,或者我应该向那些人添加 @SuppressWarnings(serial)

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

比其他方式更合适吗?

我会在任何情况下引用这类瞬态,因为我不希望它们被序列化。

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

推荐答案

给它们一个serialVersionUID,因为:

Give them a serialVersionUID, because:


  • 这是一个很好的通用做法,指定它肯定没什么坏处。

  • 警告应该被解决,而不是被抑制。

  • 有时内部类在变得足够大时会被更改为顶级类。

它是好(由于您链接的文档中陈述的所有原因)您将不会序列化这些内部类的实例。我想,如果你是偏执或担心其他开发人员可能不会做出同样好的判断,你可以通过在每个内部类中无条件抛出一个 writeObject 方法来强制执行该选择。例外。

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.

这篇关于Java:应该是可序列化的内部和外部匿名类有Seri​​alVersionUID吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆