对于我的一个项目,我需要定义一个扩展 ProviderMismatchException
的新异常.
从javadoc链接可以看出这个异常:
- 扩展
IllegalArgumentException
,它 - 扩展
RuntimeException
,它 - 扩展
Exception
,它 - 扩展
Throwable
。
除了 Throwable
添加了 private
修饰符外,它们都定义了自己的 static final serialVersionUID
。
现在,如果您实现一个接口(interface) Foo,那么所有继承的类也都实现该接口(interface),这也代表 Serializable
;但是,JDK中的子类为什么要为每个子类重新定义呢?不为继承的类重新定义它有什么危险?
最佳答案
serialVersioUID 是一个静态 long 值,因此不会通过类层次结构继承。
您需要它来指示类的先前序列化实例是否具有与当前实现相同的版本。
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.
详情请看这里:
关于java - 如果您扩展了一个实现 Serializable "down the line"的类,为什么需要重新定义 serialVersionUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245803/