为什么我的异常类需要序列化?
当您使用 Exception 类扩展类(用于创建新异常)时,您会收到一条警告,提示有一个 serialVersionUID
。我知道 serialVersionUID
在序列化和反序列化时起着重要作用,但是当我的异常需要序列化时?谁能给我一个实际案例,我希望我的自定义异常类具有序列化和反序列化功能?
When you extend a class with class Exception ( for creating new exception) you get a warning to have a serialVersionUID
. I know that serialVersionUID
plays an important role while serialization and deserialization, but when my Exception needs to be serialized? Can anyone give me a practical case in which I want my custom-exception class to have serialization and deserialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为所有异常的根类
Throwable
实现了Serialized
接口。默认情况下,所有异常都是可序列化的,这是语言设计决策,因为作者希望异常能够通过网络发送,而无需任何特殊配置。如果基类不可序列化,那么在远程方法失败的情况下,您将很难传达到底出了什么问题,因为您无法控制内置的异常类型。
This is because the root class for all exceptions,
Throwable
implements theSerializable
interface. All exceptions by default are serializable and that's a language design decision because the authors wanted exceptions to be capable of being sent across the wire without any special configuration.If the base class is not serializable, you would have a difficult time conveying what exactly went wrong in case a remote method failed since you would have no control over the built in exception types.
如果您的自定义异常曾在分布式应用程序中使用(使用 RMI、Spring http-invoker 等)并且可以从远程客户端调用的服务器方法抛出,则必须序列化异常才能跨线并去找客户。
If your custom exception is ever used in a distributed application (using RMI, Spring http-invoker, whatever) and can be thrown from a server method that is invoked from a remote client, then the exception will have to be serialized to cross the wire and go to the client.
您唯一的选择是为您定义的每个
Exception
类型定义serialVersionUID
(IDE 可以为您生成它)或抑制警告。您可能会发现我之前的问题显式serialVersionUID被视为有害?相关。
Your only options are to either define
serialVersionUID
for everyException
type you define (the IDE can generate it for you) or suppress the warning.You may find my earlier question explicit serialVersionUID considered harmful? relevant.