有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么编译器不能在编译时检测到关于可序列化声明的错误?

JavaDoc of Serializable接口的第二段:

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

为什么不能在编译时检测到此错误


共 (1) 个答案

  1. # 1 楼答案

    编译器是根据语言的要求而不是单个库来检查代码的。语言可以更改为添加关键字或注释,以执行额外的检查,并且库可以在理论上使用这些关键字或注释

    如果编译器能够以加载注释(目前仅为数据)的方式运行特定于库的检查代码,那么将非常有用。这样,编译器就可以在编译时执行额外的检查,而不必知道任何单个库的行为