Possible Duplicate:
Why Java needs Serializable interface?
根据 Java 文档中的 Serializability :
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable
为什么 Object 还没有实现 Serializable
?我们不希望被序列化的成员可以被设为transient
。为什么要阻止默认的 Serializability?
最佳答案
All subtypes of a serializable class are themselves serializable.
换句话说:您曾经创建、曾经或将要创建的所有类都是可序列化的。 transient
只排除字段,不排除整个类。
这是一个潜在的安全漏洞 - 巧合的是,您可以序列化,例如您的 DataSource
内部带有数据库凭据 - 如果此特定 DataSource
实现的创建者忘记将这些字段设置为 transient
。序列化随机 Java 对象非常容易,例如通过持有对外部 this
的隐式引用的内部类。
使用您明确想要并允许序列化的类的白名单更安全,而不是仔细检查您的代码,确保没有您不想要的字段被序列化。
此外,您不能再说:MySuperSecretClass
不可序列化(通过简单地不实现 Serializable
) - 您只能排除胆量(字段)。
关于java - 为什么 java.lang.Object 不实现 Serializable 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11600213/