What is object serialization?

前端 未结 14 2117
长发绾君心
长发绾君心 2020-11-21 23:23

What is meant by \"object serialization\"? Can you please explain it with some examples?

14条回答
  •  旧巷少年郎
    2020-11-22 00:03

    |*| Serializing a class : Converting an object to bytes and bytes back to object (Deserialization).

    class NamCls implements Serializable
    {
        int NumVar;
        String NamVar;
    }
    

    |=> Object-Serialization is process of converting the state of an object into steam of bytes.

    • |-> Implement when you want the object to exist beyond the lifetime of the JVM.
    • |-> Serialized Object can be stored in Database.
    • |-> Serializable-objects cannot be read and understood by humans so we can acheive security.

    |=> Object-Deserialization is the process of getting the state of an object and store it into an object(java.lang.Object).

    • |-> Before storing its state it checks whether serialVersionUID form input-file/network and .class file serialVersionUID are same.
        If not throw java.io.InvalidClassException.

    |=> A Java object is only serializable, if its class or any of its superclasses

    • implements either the java.io.Serializable interface or
    • its subinterface, java.io.Externalizable.

    |=> Static fields in a class cannot be serialized.

    class NamCls implements Serializable
    {
        int NumVar;
        static String NamVar = "I won't be serializable";;
    }
    

    |=> If you do not want to serialise a variable of a class use transient keyword

    class NamCls implements Serializable
    {
        int NumVar;
        transient String NamVar;
    }
    

    |=> If a class implements serializable then all its sub classes will also be serializable.

    |=> If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case,
    NotSerializableException is thrown at runtime.

提交回复
热议问题