您的位置:首页 > 编程语言 > Java开发

java源码阅读之序列化Serializable

2019-03-30 20:40 211 查看

总结

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

  • 没有实现Serializable接口的类不能序列化或反序列化,所有可序列化类的子类也可序列化

  • To allow subtypes of non-serializable classes to be serialized, 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.

  • 为了让非序列化类的子类也可以序列化,被继承的类必须有一个可访问的无参构造函数去初始化类的状态,如果不这样的话运行的时候会报错

  • Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures

  • 序列化和反序列化时需要特殊操作的类必须实现特殊的方法

private void writeObject(java.io.ObjectOutputStream out) throws IOException

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException

private void readObjectNoData() throws ObjectStreamException

  • The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.A serializable class can declare its own serialVersionUID explicitly by declaring a field named

    “serialVersionUID”
    that must be static, final, and of type
    long

  • 每一个可序列化的类序列化时都有一个叫做serialVersionUID的版本数字,它在反序列化时用来验证序列化对象的发送方和接收方都加载了希望通过序列化来实现兼容性的对象的类,一个序列化类可以通过声明一个静态的long类型的变量"serialVersionUID"声明自己的UID

  • If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java™ Object Serialization Specification.

  • 如果一个序列化类没有明确声明自己的UID, 序列化时会根据类的不同方面计算出一个默认的UID, 正如JAVA Object Serialization Specification描述的那样。

  • However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected

    InvalidClassException
    s during deserialization.

  • 然而强烈的推荐对可序列化类明确地声明UID,因为默认计算出来的UID对类的细节非常敏感以至于非常依赖实现的编译器,所以因此在序列化时会导致一些意想不到的InvalidClassException

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: