Serialize and deserialize

1. Basic Concepts

1. What is serialization and deserialization

( 1 ) Serialization: Serialization converts objects into byte streams for transmission over the network or storage in local files.

( 2 ) Deserialization: After the client obtains the serialized object byte stream from the file or the network, it reconstructs the object through deserialization according to the object state and description information saved in the byte stream.

( 3 ) Essentially: serialization is to write the state of the entity object into the ordered byte stream according to a certain format, and deserialization is to reconstruct the object from the ordered byte stream and restore the object state.

2. Why do we need serialization and deserialization?

We know that when two processes communicate remotely, they can send various types of data to each other, including text, pictures, audio, video, etc., and these data will be transmitted over the network in the form of binary sequences.

So when two Java processes communicate, can object transfer between processes be realized? The answer is yes! How to do it? This requires Java serialization and deserialization!

In other words, on the one hand, the sender needs to convert the Java object into a sequence of bytes, and then transmit it over the network; on the other hand, the receiver needs to recover the Java object from the sequence of bytes.

3. The benefits of Java serialization

One is: data persistence is realized, and data can be permanently saved to the hard disk through serialization; the other is: remote communication , that is, the byte sequence of the object is transmitted on the network.

Real column:

public class Dog implements Serializable {
    private static final long serialVersionUID = -8742448824652078965L;

    private String name;
    private Integer age;

    public Dog(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        System.out.println("setName");
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Test {

    static String FILE_NAME = "C:/obj.txt";

    public static void main(String[] args) throws Exception {

        Dog dog = new Dog("小花", 10);

        serialize(dog, FILE_NAME);

        Object obj = unSerialize(FILE_NAME);

        System.out.println(((Dog)obj).toString());

    }


    public static void serialize(Object object, String fileName) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        objectOutputStream.close();
        fileOutputStream.close();
    }

    public static Object unSerialize(String fileName) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(fileName);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        Object obj = objectInputStream.readObject();
        objectInputStream.close();
        fileInputStream.close();
        return obj;
    }
}

2. Relevant matters needing attention

1. When serializing, only the state of the object is saved, regardless of the method of the object; member methods cannot be serialized

2. When a parent class implements serialization, the subclass automatically implements serialization, and there is no need to explicitly implement the Serializable interface;

3. When the instance variable of an object refers to other objects, the reference object is also serialized when the object is serialized;

4. Not all objects can be serialized. As for why not, there are many reasons, such as:

For security reasons, for example, an object has fields such as private       and public . For an object to be transmitted, such as writing to a file, or performing RMI transmission, etc., in the process of serialization and transmission, the private and other fields of this object are is unprotected;

·       Resource allocation reasons, such as socket and thread classes, if they can be serialized, transmitted or saved, they cannot be re-allocated, and there is no need to do so;

5. Member data declared as static and transient types cannot be serialized. Because static represents the state of the class, transient represents the temporary data of the object.

6. The serialization runtime associates each serializable class with a version number called serialVersionUID , which is used during deserialization to verify that the sender and receiver of the serialized object are loaded for that object Classes compatible with serialization. serialVersionUID can not be written . Give it an explicit value. Explicitly defining serialVersionUID serves two purposes:

In       some cases, it is hoped that different versions of a class are compatible with serialization, so it is necessary to ensure that different versions of a class have the same serialVersionUID ;

·       In some cases, you do not want different versions of a class to be serialized compatible, so you need to ensure that different versions of a class have different serialVersionUIDs .

7. There are many basic classes in Java that have implemented the serializable interface, such as String, Vector , etc. But there are also some that do not implement the serializable interface;

8. If the member variable of an object is an object, then the data members of this object will also be saved! This is an important reason why serialization can be used to solve deep copy;

9. The A -side serializes the object, and the B -side deserializes the object. The extra field values ​​on the A-side will be ignored by the B -side; the extra fields on the B -side will be set to default values.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733099&siteId=291194637