使用serialVersionUID还是禁止警告? [英] Use the serialVersionUID or suppress warnings?

查看:167
本文介绍了使用serialVersionUID还是禁止警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类,例如,扩展HttpServlet?我的编译器警告我,我的类应该有一个serialVersionUID。如果我知道这个对象永远不会被序列化,我应该定义它还是添加注释来抑制这些警告?

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?

推荐答案

我不了解Java最佳实践,但我发现如果你声称序列化永远不会发生,你可以添加一个抛出的writeObject方法。然后禁止警告,知道它不可能适用于你。

I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you.

否则有人可能在将来通过父类序列化您的对象,并最终得到一个默认序列化表格其中:

Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where:


  • 表单在不同版本的代码之间不兼容。

  • 你已经压制了这种情况的警告。

添加一个ID听起来像一个小屋,因为你真正想要的do不是序列化。期望调用者不要序列化你的对象意味着你希望他们在他们的HttpServlet属于你的类时知道。对于拥有一个不能序列化的Serializable对象而言,这种多态性的破坏就在您的头上,而您至少可以做的就是确保不知情的调用者知道它。

Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it.

这篇关于使用serialVersionUID还是禁止警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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