简体   繁体   English

在Serializable类中使用私有构造函数扩展类

[英]Extending class with private constructor in Serializable class

The document detailing Serializable on http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html上详细介绍了Serializable的文档

says

"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." “为了允许序列化不可序列化类的子类型,该子类型可以承担保存和恢复超类型的公共,受保护和(如果可访问)包字段状态的责任。只有当该类可以将其继承时,该子类型才可以承担此责任。 extend具有可访问的no-arg构造函数,用于初始化类的状态。如果不是这样,则声明类Serializable是错误的。将在运行时检测到该错误。”

In general any class with private constructor cannot be extended. 通常,任何带有私有构造函数的类都不能扩展。 And this error will be visible on compile time. 并且此错误将在编译时可见。 But the last line the above documentation says it will occur at run time. 但是上述文档的最后一行说它将在运行时发生。 Any explanations? 有什么解释吗?

The document says that a non-serializable supertype needs a no-arg constructor. 该文件说,不可序列化的超类型需要一个无参数的构造函数。 It does not say it should be private. 它并没有说它应该是私有的。 On the contrary it says this constructor should be accessible. 相反,它表示此构造函数应该可访问。 What the documentation means about runtime is this 文档对运行时的意义是什么

class A {
    A() {   <-- accessible only in current package
    }
}

public class B extends A implements Serializable {
    public B() {
    }
}

Lets assume both A and B are in the same package. 假设A和B都在同一个程序包中。 There is no compile error. 没有编译错误。 But if we try to deserialize an instance of B from class C in another package we will get a runtime exception, because ObjectInputStream will try to invoke A's no-arg constructor but it is inaccessible from outside the package 但是,如果我们尝试从另一个包中的类C反序列化B的实例,则会得到运行时异常,因为ObjectInputStream会尝试调用A的no-arg构造函数,但无法从包外部访问它

Your last part of explanation is not correct. 您最后的解释是不正确的。 It doesn't matter if A's no-arg constructor is visible to C or not. A的no-arg构造函数是否对C可见并不重要。 It only needs to be visible to B. 它只需要对B可见。

In a nut shell, B can be declared serializable as long as A has a no-arg constructor which is visible to B. 在坚果壳中,只要A具有对B可见的无参数构造函数,就可以将B声明为可序列化的。

But the original is still open: 但是原来还是开放的:

Why this error is identified during run time when all validation information is available during compile time? 当所有验证信息在编译期间可用时,为什么在运行时识别此错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM