gpt4 book ai didi

java - 为什么 Java 在 Exception 和 Throwable 类中声明 serialVersionUID?

转载 作者:行者123 更新时间:2023-11-30 08:50:30 25 4
gpt4 key购买 nike

<分区>

当我像下面这样创建一个自定义异常类时

public class MyApppException extends Exception {

private String message = null;

public MyApppException() {
super();
}
public MyApppException(String message) {
super(message);
this.message = message;
}
public MyApppException(Throwable cause) {
super(cause);
}
}

编译器给我低于衰减

The serializable class InsufficientBalanceException does not declare a static final serialVersionUID field of type long

从 Java 文档我理解了 serialVersionUID 的含义

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:

但是我不明白Java为什么要在ExceptionThrowable类中声明serialVersionUID? ExceptionThrowable 类中的 serialVersionUID 有什么用?真的需要吗?如果是,为什么?有人请澄清。

异常

public class Exception extends Throwable {
static final long serialVersionUID = -3387516993124229948L;

可抛

public class Throwable implements Serializable {
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -3042686055658047285L;

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com