关于The serializable class XXX does not declare a static final serialVersionUID field of type long的警告

今天在写Java版本的Spark的一个练习的时候,遇到了一个警告:The serializable class  does not declare a static final serialVersionUID field of type long。在之前没有遇到这类问题的情况下,进行了google,发现了一段在javadoc中Serializable的描述:

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. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class–serialVersionUID fields are not useful as inherited members. 

它的意思是说:serialVersionUID被用来作为Java对象序列化中的版本标示,如果一个序列化类没有声明这样一个static final的产量,JVM会根据各种参数为这个类计算一个。对于同样一个类,不同版本的JDK可能会得出不同的serivalVersionUID。而SerialVersionUID的作用是: 在进行序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。

但只要任何类别实现了Serializable这个接口的话,如果没有加入 serialVersionUID,Eclipse都会给出warning警告,这个serialVersionUID是为了让该类别 Serializable向后兼容。 

在代码中可以随便写一个serialVersionUID,而在Eclipse中它会帮助生成一个,且有两种生成方式: 

一个是默认的1L(Add default serial version ID):private static final long serialVersionUID = 1L; 

一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段(Add qenerated servial version ID),如:private static final long serialVersionUID = -7469021523456975052L; 

当一个类实现了Serializable接口,但没有定义serialVersionUID,Eclipse会提示去定义它。如果不想定义它,就在Eclipse的设置中将它关掉,设置如下: Window ==> Preferences ==> Java ==> Compiler ==> Error/Warnings ==> Potential programming problems。将Serializable class without serialVersionUID的warning改成ignore即可。

考虑到兼容性问题,我将serialVersionUID设定为默认的1L。

你可能感兴趣的:(Spark相关)