Use the serialVersionUID or suppress warnings?

2019-01-21 21:05发布

I want to create a class that, for example, extends HttpServlet? My compiler warns me that my class should have a serialVersionUID. If I know that this object will never be serialized, should I define it or add an annotation to suppress those warnings?

What would you do and why?

12条回答
Evening l夕情丶
2楼-- · 2019-01-21 21:42

Even if you know this object will be serialized there is no need to generate serialVersionUID because java will automatically generate it for you and will automatically keep track of changes so your serialization will always work just fine. You should generate it only if you know what you are doing (backward serialization compatibility, manual change tracking etc.)

So I would say suppressing the warning is the best and safest solution in most cases.

查看更多
Melony?
3楼-- · 2019-01-21 21:43

If you do not plan to serialize instances, add a SuppressWarning.

A generated serial ID can be a bit dangerous. It suggests that you intentionally gave it a serial number and that it is save to serialize and deserialize. It's easy to forget to update the serial number in a newer version of your application where your class is changed. Deserialization will fail if the class fields have been changed. Having a SuppressWarning at least tells the reader of your code that you did not intend to serialize this class.

查看更多
Juvenile、少年°
4楼-- · 2019-01-21 21:44
Viruses.
5楼-- · 2019-01-21 21:45

That warning drives me crazy, because every time you subclass a Swing class, you know you're never going to serialize it, but there is that stupid warning. But yeah, I let Eclipse generate one.

查看更多
放我归山
6楼-- · 2019-01-21 21:48

If you leave out a serialVersionUID java will generate one for the class at compile time (it changes with every compilation).

When deserializing objects the serialVersionUID of the deserialized object is compared to that of the class in the jvm. If they are different they are considered incompatible and an Exception is thrown. This can happen for instance after upgrading your program and deserializing old classes.

I always use 1L for serialversionUID. It doesn't hurt (compared to the default generated) and it still leaves the option of breaking compatibility later by incrementing the id.

查看更多
疯言疯语
7楼-- · 2019-01-21 21:49

It is good to generate SVUID to every class implementing serializable. The reason is simple. You never know when it will be serialized by you or by some 3rd party. There can be configured a lot of services which will serialize servlets. For every IDE exists plugin which generates one or just use template and set svuid = 1L.

查看更多
登录 后发表回答