Java serialVersionUID作用和生成

序列化和反序列化
Java是面向对象的语言,与其他语言进行交互(比如与前端js进行http通信),需要把对象转化成一种通用的格式比如json(前端显然不认识Java对象),从对象到json字符串的转换,就是序列化的过程,反过来,从json字符串转换成Java对象,就是反序列化的过程。

serialVersionUID是什么
反序列化的过程,需要从一个json字符串生成一个Java对象。典型的如下:

Gson gson = new Gson();
Request req = gson.fromJson("request string", Request.class)


这时候会有问题,需要验证输入的json字符串是否是从当前的Request这个类序列化过去的,serialVersionUID就是用来干这个的。当序列化的时候的serialVersionUID与反序列化的时候的serialVersionUID不一致的时候,会跑出InvalidCalssException。
如果没有显式地定义一个serialVersionUID,那么Java会默认根据类信息计算一个serivalVersionUID出来。

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long: 
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; 
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.

 

如何生成
Intellij IDEA可以自动为serializable的类生成一个serialVersionUID。
Preferences - Inspection - Serializable class without ‘serialVersionUID’ 勾选。

这样,如果没有申明serialVersionUID属性,编辑器就会给出提示,按alt + Enter 可以快速生成。

 

这样在没有serialVersionUID的类中,可以自动根据提示生成serialVersionUID了。

喜欢这篇文章?欢迎打赏~~

 

posted @ 2018-12-09 10:29  苍青浪  阅读(12797)  评论(2编辑  收藏  举报