为什么 scala.Serialized 没有指定任何方法?
因为 Java 语言要求所有接口成员都是公共的,而最初的设计者并不想强制 java.io.Serialized
的“方法”是公共的,所以这在 Java 中是不可能的。
Scala 没有此限制,但 readObject
/writeObject
之类的内容仍然没有在 scala.Serialized
特征中指定。
这不会对开发人员有帮助吗,因为
- 他们可以保证他们的签名是正确的,
- 这会让访问这些方法变得不那么尴尬。
还是我错过了一些重要的事情?
Because the Java language required all interface members to be public and the original designers didn't want to force the "methods" of java.io.Serializable
to be public, this was not possible in Java.
Scala doesn't have this restriction, but things like readObject
/writeObject
are still not specified in the scala.Serializable
trait.
Wouldn't this help developers because
- they had a guarantee that their signature is correct
- it would make accessing these methods less akward.
or do I miss something important?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你知道。
readObject/writeObject 方法必须是私有的并且不能被重写才能使机制正常工作。
它们也以相反的方式调用(即超类->类)。此外,您确实希望该方法保持私有以防止误用(和显式调用)
可序列化机制还提供其他方法:如 writeReplace+readResolve,通常不在同一个类中使用 + readObjectNoData(这不是很有用)。
现在,如果您需要特定方法,请查看 java.io.Externalized。它确实发布了它的方法,并且实现它会覆盖默认的序列化机制。
Yes, you do.
readObject/writeObject methods have to be private and NOT overridden for the mechanism to work properly.
They are called in reverse way (i.e. superclass->class) too. Morealso you do wish that the method remains private to prevent misuse (and explicit calls)
Serializable mechanism offers other methods as well: like writeReplace+readResolve, that are usually not used in the same class + readObjectNoData (that's not so useful).
Now if you need specific method take a look at java.io.Externalizable. It does publish its methods and implementing it overrides the default serialization mechanism.
从 Java 背景回答,但我猜同样的推理也适用于 Scala:Java 不需要标记为可序列化的方法来实现任何方法;运行时本身提供序列化机制。这就是为什么界面是空的。 readObject 和 writeObject 不是 Serialized 的一部分,不是因为它们不是公共的,而是因为从 Serialized 派生的对象不需要实现它们。
Serialized 实际上不应该是一个接口,而应该是一个注释(特别是因为从 Serialized 类派生的类本身很可能不是),但在语言拥有注释之前它就是该语言的一部分。
Answering from a Java background but I would guess the same reasoning applies to Scala: Java does not require methods marked Serializable to implement any methods; the runtime provides the serialization mechanism itself. That's why the interface is empty. readObject and writeObject are not part of Serializable not because they aren't public but because objects derived from Serializable don't need to implement them.
Serializable really shouldn't be an interface but an annotation (especially because a class derived from a Serializable class may very well not be Serializable itself), but it was part of the language before the language had annotations.
连载中没有公开的方法。您可以实现四种方法,但它们都是可选的。你的问题没有意义。
There are no methods to make public in serialization. There are four methods you may implement but they are all optional. Your question doesn't make sense.