javaexceptionserialization

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


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 ?


Solution

  • 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.