Why can't the compiler detect this error regarding Serializable declaration at compile time?

强颜欢笑 提交于 2019-12-23 19:13:27

问题


From second paragraph of JavaDoc of Serializable interface :

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.

Why can't this error be detected at compile time ?


回答1:


The compiler is designed to check the code based on the requirements of the language, not an individual library. The language could be changed to add a keyword or annotation which perform additional checks and the library could use those in theory.

What would be useful is if the compiler could run library specific checking code in the way it can load annotations (which are currently purely data) This way additional checks could be performed at compile time without it knowing the behaviour of any individual library.



来源:https://stackoverflow.com/questions/12067967/why-cant-the-compiler-detect-this-error-regarding-serializable-declaration-at-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!