What are the three questions?

Three popular questions about life are:

Who am I? Where am I from? Where am I going?

Just like the Tang Priest in Journey to the West introduces himself like this every time:

Tang Sanzang, a poor monk, came from the Eastern Part of the Tang Dynasty and went to the west to fetch buddhist scriptures.

Today, however, I’m not here to answer my own questions about life, but to explain the serialized meaning of life through similar three-way thinking, the What-Why-How trilogy.

What? What is serialization?

Serialization refers to a mechanism for converting an object into a stream of objects. We can think of it as a transformation of the two modes of existence of object data.

According to? Why serialization?

After understanding the concept, we can think clearly and deeply that since there are two ways of existence of objects, there must be a complementary relationship, and objects can not do things, let the object flow to do. So what can object streams do?

Let’s start with a question:

What is flow?

A “stream” is an abstraction that represents any data source object capable of producing data or receiving data. “Streaming” hides the details of processing data in the actual input/output device. A program can open a stream at a data source and read the data from that stream into the program in sequence. Such a stream is called an input stream. A program can also open a destination stream and sequentially write data from the program to the destination. Such streams are called output streams.

We can think of it as a flow of water, whether it’s apple juice or orange juice, when it turns into a liquid, it’s a flow. As for the direction of input and output, the one that goes out is called the output stream, and the one that flows in is the input stream. However, for these words, the direction of the same stream may be different depending on the reference, so it is necessary to specify a reference. For Android, the reference is memory, and everything that comes Out of memory is Out, and everything that comes In is In.

There are also two types of streams: byte streams and character streams in terms of their data types. From the point of view of the existence of flow, it can be divided into buffer flow and node flow. Byte stream and character stream, as their names suggest, data in a stream exists in characters and bytes, respectively. Buffer flow and node flow. Node flow refers to reading and writing data from or to a specific place (node), and processing flow: it is the connection and encapsulation of an existing stream, and data reading and writing functions are realized through function calls of the encapsulated stream. To use the analogy of water flow, the flow that has a source of water and flows into the source is called nodal flow, and the part in the middle that passes through some places and changes the velocity is called buffer flow, such as the Sanmenxia Dam.

Moreover, a stream cannot exist alone. There must always be an input and an output. Just like a river, it is called a stream only when it has a source and an estuary. If it is still in one place, it is a lake, not a river.

What can flow do?

This problem is explained in the concept of flow: shielding the actual input/output side from the details of processing data. Because of this property, streams are used for data transfer. Such as:

  • Data transfer between server and client
  • Data transfer between local files and clients
  • Data transfer between associated pages within the client

After answering these questions, do you know why serialization is required?

The answer is because of a purpose that requires data to be turned into a stream.

How? How is serialization implemented?

For Android developers, there are two options for serialization:

  • Serializable
  • Parcelale

Serializable is the serialization interface provided by Java, and Parcelale is the new serialization method provided by Android. The difference between the two will be discussed later, but for now we will experience the serialization of the two implementations.

Serializable

The Serializable interface is an empty interface whose sole purpose is to declare that the class implementing it can be serialized.

public class UserBean implements Serializable{ public int id; public String name; public UserBean(int id, String name) { this.id = id; this.name = name; }}Copy the code

Serializing a Serializable object is as simple as a few simple steps.

// Create a serialized object UserBean UserBean = new UserBean(666,"Xiao Ming"); FileOutputStream FileOutputStream = new FileOutputStream(fileName); ObjectOutputStream = new ObjectOutputStream(fileOutputStream); / / write object objectOutputStream. WriteObject (the userBean); // Close the stream objectOutputStream.close();Copy the code

Deserialization is also very simple, converting a file to a file input stream in reverse, a file input stream to an object stream, and finally to an object.

FileInputStream = new FileInputStream(fileName); ObjectInputStream ObjectInputStream = new ObjectInputStream(fileInputStream); / / read the UserBean object the UserBean = (the UserBean) objectInputStream. ReadObject (); Objectinputstream.close ();Copy the code

There is some doubt:

When an object is converted into an object, what is it identified by?

In the above case, if the UserBean class added the address field after serialization, can the unsequence conversion succeed?

The answer is NO!

The reason is that Java creates the serialVersionUID field by default when implementing the Serializable interface. The default serialVersionUID of the Java class automatically changes when a field in the class is modified, so the exception occurs.

More specifically, during Java serialization, the system will write the serialVersionUID of the current class into the serialization file. During deserialization, the system will check the serialVersionUID in the file. Check whether it is the same as the serialVersionUID of the current class. If it is, it indicates that the version of the serialized class is the same as that of the current class. Deserialization succeeds; otherwise, it fails.

In real projects, entity field changes are quite common, and to avoid this, it is best to create the serialVersionUID manually.

Private static Final Long serialVersionUID = 64893744941884305L;Copy the code

A long handwritten list is also impractical, but don’t panic, with the help of development tools, it can be generated automatically for us.

  • The first step is to turn on the check that no warning is created for the occurrence of this field in the Serializable implementation class. Setting-> Conforms ->Java->Serialization Issues ->Serializable Class Without ‘serialVersionUID’

  • Second, after this is selected, Alt+Enter on the class name will prompt you to automatically create the serialVersionUID in the class with the warning.

Parcelale

Here is another serialization method, Parcelale. Parcelale is also an interface that implements object serialization and deserialization.

Unlike Serializable, Parcelale is a token empty interface that implements several methods internally. The source code is as follows. The serialization method is completed by writeToParcel method, and the deserialization is completed by Creator.

public interface Parcelable { int CONTENTS_FILE_DESCRIPTOR = 1; int PARCELABLE_WRITE_RETURN_VALUE = 1; int describeContents(); void writeToParcel(android.os.Parcel parcel, int i); static interface ClassLoaderCreator <T> extends android.os.Parcelable.Creator<T> { T createFromParcel(android.os.Parcel parcel, java.lang.ClassLoader classLoader); } static interface Creator <T> { T createFromParcel(android.os.Parcel parcel); T[] newArray(int i); }}Copy the code

Here is a small example of comparison:

Public class BookBean implements Parcelable{public int id; public String name; public BookBean(int id, String name) { this.id = id; this.name = name; Public class BookBean implements Parcelable{public int id; public String name; public BookBean(int id, String name) { this.id = id; this.name = name; } protected BookBean(Parcelin) {
        id = in.readInt();
        name = in.readString();
    }

    @Override
    public String toString() {
        return "BookBean{" +
                "id=" + id +
                ", name='" + name + '\''+'}'; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(name); } @Override public int describeContents() { return 0; } public static final Creator
      
        CREATOR = new Creator
       
        () { @Override public BookBean createFromParcel(Parcel in) { return new BookBean(in); } @Override public BookBean[] newArray(int size) { return new BookBean[size]; }}; }
       
      Copy the code

Code changes a lot, how many fields, it is estimated to be crazy to write, but do not panic, Android Studio to help you, Alt + Enter can choose automatic code generation, it is not too cool.

Serializable VS Parcelale

Both methods can implement serialization and both can be used to deliver data to intEnts.

You think so:

  • A: the Serializable
  • B: Parcelale

You could have done it this way:

  • C: Serializable and Parcelale

Serializable is a Serialization rescue in Java. It is simple to use but expensive. Serialization and deserialization require a lot of IO operations. Parcelable is the serialization method in Android, so it is more suitable for The Android platform. The disadvantage of Parcelable is that it is a little more difficult to use, but it is very efficient. Therefore, Serializable is recommended when an object is serialized to a network transport or hardware storage device. Parcelable is recommended for in-memory manipulation of passing data.

The last

The two serialization options are recommended from “Android Development Art Exploration”. As for why Serializable memory overhead is high, Parcelable efficiency is high, need to analyze the deeper principle, I will study it when I have time, another article. If you have any friends, please leave a comment below to discuss the exchange.

Welcome to pay attention to the wechat public account of the blogger, quickly join, look forward to growing with you!