This column focuses on sharing the knowledge of large-scale Bat interview, and it will be updated continuously in the future. If you like it, please click a follow
Hermes architecture Github address is available across the process of EventBus Github address more complete project download. To be continued. The source code. Github. You can click about me to contact me
Interviewer: Serialization and deserialization of Android, Parcelable and Serializable difference Serialization and deserialization can be an important topic in the interview, sometimes slightly wrong, the interviewer will think that the development of the candidate: should start with Parcelable and Serializable use
As an architect, I will share some essential knowledge points here and enumerate the direction of my preparation:
Serialization and deserialization
At the bottom of the system, data transmission is in the form of simple byte sequence transmission, that is, at the bottom, the system does not know objects but only byte sequence. In order to achieve the purpose of process communication, data serialization is needed first, and serialization is the process of converting objects into byte sequence. Conversely, when the byte sequence is shipped to the corresponding process, the process, in order to recognize the data, deserializes it, that is, converting the byte sequence into an object. With that in mind, let’s look at two interfaces for serialization and deserialization: Serializable and Parcelable.
Second, Serializable interface
Java provides a serialization interface, the Serialable interface, which is defined in the documentation as follows: Marks classes that can be serialized by ObjectOutputStream and deserialized by ObjectInputStream. ObjectOutputStream and ObjectInputStream do the serialization and deserialization of the current class. ObjectOutputStream and ObjectInputStream do the serialization and deserialization of the current class. Reading through the documentation, we find that the interface requires us to declare a variable in the class that implements the interface as follows:
private static final long serialVersionUID= 1L;
Copy the code
What’s the use of this variable? If you didn’t specify this value manually, you first serialized classA, got file A, and then changed the internal structure of classA, such as adding A new variable, the deserialization would fail, because in fact the system would automatically calculate A serialVersionUID value at serialization time. If classA is changed, the system will recalculate a new serialVersionUID value during deserialization, and the two values will not be equal, and deserialization will fail. Therefore, manually specifying a value can save data to a large extent and prevent data loss.
Next, let’s look at the steps for serialization and deserialization:
- Object serialization:
Instantiate an object output stream:ObjectOutputStream
The object output stream can wrap an output stream, such as a file output stream.
(2) UseObjectOutputStream.writeObject(obj)
Write objects. - Deserialization of objects:
(1) Instantiate an object input stream:ObjectInputStream
The object input stream can wrap an input stream, such as a file input stream.
(2) UseObjectInputStream.readObject(obj)
Read objects.
The following is an example of how to implement serialization and deserialization:
package com.chenyu.serialable; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; public int id; public String username; public String email; public User(int id, String username, String email) { this.id = id; this.username = username; this.email = email; }}Copy the code
②Test tests whether serialization and deserialization are successful:
package com.chenyu.serialable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Test { public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {// instantiate User User =new User(1,"TestName"."[email protected]"); ObjectOutputStream ObjectOutputStream = new ObjectOutputStream(new FileOutputStream("test.txt"));
objectOutputStream.writeObject(user);
objectOutputStream.close();
System.out.println("Serialization successful!"); ObjectInputStream ObjectInputStream =new ObjectInputStream(new FileInputStream("test.txt"));
User newUser = (User) objectInputStream.readObject();
objectInputStream.close();
System.out.println("Deserialization successful!");
System.out.println("ID:"+newUser.id+" username:"+newUser.username+" Email:"+newUser.email); }}Copy the code
Run test.java and get the following result:
Note:
Static member variables are classes, not objects, so they do not participate in serialization; Member variables marked with the TRANSIENT keyword do not participate in the serialization process.
3. Parcelable interface
Next up is the Parcelable interface, which is a new serialization method provided by Android. First, take a look at the official documentation for this interface:
Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface.
In addition to the methods that implement this interface, you create a static object called CREATOR that implements an anonymous inner class of Parcelable. CREATOR. The following is a typical example of a class that implements the Parcelable interface:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
returnnew MyParcelable[size]; }}; private MyParcelable(Parcelin) { mData = in.readInt(); }}Copy the code
Here are the functions of the above methods:
- ①writeToParcel(Parcel out,int flags): writes the current object to the serialization structure.
- ②createFromParcel(Parcel in): Creates the original object from the serialized object
- ③newArray(int size): creates the original object array of the specified length
- ④MyParcelable(Parcel in): Creates the original object from the serialized object
WriteToParcel is responsible for serializing objects, while CREATOR is responsible for deserializing data. As long as your class implements the Parcelable interface and implements the above methods, it can automatically serialize and deserialize objects.
WriteInt (data); writeInt(data); writeToParcel; writeInt(data);
out.writeInt(id);
out.writeString(name);
out.writeString(email);
Copy the code
After doing so, the corresponding MyParcelable(Parcel in) deserialization method must also read:
in.readInt();
in.readString();
in.readString();
Copy the code
That is, the order should correspond one to one, otherwise, the data extracted will be wrong. So far, Serialable interface and Parcelable interface have been introduced, which are basic concepts in IPC mechanism and should be mastered. I hope my article can help you in your study.
4 Parcelable and Serializable differences:
Android custom objects can be serialized with two options: Serializable and Parcelable
1. Why do objects need to be serialized
- Permanently saves an object, saving its byte sequence to a local file.
- Pass objects across the network by serializing them.
- Pass objects between processes by serializing them.
2. How to choose the interface to use when an object needs to be serialized
- When using memory
Parcelable
thanSerializable
High performance. Serializable
A large number of temporary variables are generated during serialization, leading to frequent GC (memory reclamation).
3.Parcelable cannot be used to store objects on disk because Parcelable does not do a good job of ensuring data persistence when the outside world changes. An intelligent, innovative and easy to use Android interprocess Communication (IPC) framework. (Easy-to-use Android IPC framework for inter-progress communication)
Hermes architecture Github address is available across the process of EventBus Github address more complete project download. To be continued. The source code. Github. You can click about me to contact me