Principles and differences between Android Serializable and Parcelable

Source: Internet
Author: User
Tags object serialization

 

I. What is serialization and deserialization? (1) serialization of GLOSSARY objects: the process of converting Java objects into byte sequences and storing them to a storage medium.
Object deserialization: the process of restoring the byte sequence to a Java object.
(2) serialization details Object serialization involves three key points: Java object, byte sequence, and storage.

1. Composition of Java objects?
Java objects include variables and methods. However, sequences and deserialization only process Java variables, but not methods. Sequences and deserialization only process data.

2. What is a character sequence?
Character sequences are two words, Character is in the computer and telecommunications fields, Character (Character) is an information unit. In mathematics, sequences are objects (or events) in a column ).
Character-Wikipedia and sequence-Wikipedia are a set of consecutive characters. Similar to 1A165613246546

3. Storage
The character sequence must be stored in one place, either hard disk or memory.
The simple saying is: serialization saves the current object information. Deserialization is the opposite.


Ii. What is the difference between Java object serialization and Java object serialization? The premise of a Java object must exist during the JVM runtime. If you want to obtain the specified Java object without JVM running or on the JVM of another machine, it is impossible to complete the existing Java object mechanism.
Unlike Java objects, if Java objects are serialized, the principle is to save the Java object information to the storage media, therefore, you can still use Java objects in two situations where the preceding Java objects cannot exist.


Iii. Why serialization and deserialization? Based on the above understanding of serialization and deserialization, this question can be translated into: Why do we need to save the object information to the storage media and then read it?
As explained in section 2, developers need to obtain the specified Java object on a JVM that is not running on the JVM or on other machines.


4. What is the difference between Serializable and Parcelable in Android? The two are used to support serialization and deserialization. The biggest difference between the two is that the storage media is different. Serializable uses IO to read and write data on the hard disk, while Parcelable directly reads and writes data in the memory, obviously, the memory read/write speed is usually higher than the IO read/write speed, so Parcelable is usually preferred in Android.
Serializable is not the focus of current attention, but you can view the simple Serializable example in the article "Java serialization algorithm Dialysis" to view the IO files generated by serialization, it also reads in hexadecimal notation and explains the meaning of each hexadecimal number one by one.


V. Parcelable example: classes that implement the Parcelable interface in Android support sequence and deserialization. The following is an example of implementation:
1. Implement the Parcelable Interface
2. Add Object Attributes
3. overwrite the writeToParcel (Parcel dest, int flags) method to specify the data written to the Parcel class.
4. create Parcelable. the Creator static object has two methods: createFromParcel (Parcel in) and newArray (int size). The former specifies how to read data objects from Parcel and the latter creates an array.
5. Override the describeContents method. 0 is returned by default.
Public class Gril implements Parcelable {private int mAge; // age private boolean mSexy; // whether it is sexy @ Override public void writeToParcel (Parcel dest, int flags) {dest. writeInt (mAge); dest. writeByte (byte) (mSexy? 1: 0);} public static final Parcelable. Creator
 
  
CREATOR = new Parcelable. Creator
  
   
() {Public Gril createFromParcel (Parcel in) {Gril gril = new Gril (); gril. mAge = in. readInt (); gril. mSexy = in. readByte ()! = 0; return gril;} public Gril [] newArray (int size) {return new Gril [size] ;};@ Override public int describeContents () {return 0 ;}}
  
 


Vi. Parcelable Principle

As shown in the preceding example, the specific write (dest. writeInt (mAge);) and read (gril. mAge = in. readInt ();) is the operation on the Parcel object. The following is the definition of Parcle reading and writing int data.

 

public final class Parcel {    ......        /**     * Write an integer value into the parcel at the current dataPosition(),     * growing dataCapacity() if needed.     */    public final native void writeInt(int val);    /**     * Read an integer value from the parcel at the current dataPosition().     */    public final native int readInt();         ......}


 

From the code above, we can see that all native methods use JNI, which is located in system/frameworks/base/core/jni/android_util_Binder.cpp. The following uses int-type read/write as an example.

static void android_os_Parcel_writeInt(JNIEnv* env, jobject clazz, jint val){    Parcel* parcel = parcelForJavaObject(env, clazz);    if (parcel != NULL) {        const status_t err = parcel->writeInt32(val);        if (err != NO_ERROR) {            jniThrowException(env, java/lang/OutOfMemoryError, NULL);        }    }}static jint android_os_Parcel_readInt(JNIEnv* env, jobject clazz){    Parcel* parcel = parcelForJavaObject(env, clazz);    if (parcel != NULL) {        return parcel->readInt32();    }    return 0;}


From the above, we can see that the Parcel implementation is called and the writeInt32 and readInt32 functions are called respectively. Next, let's take a look at the specific implementation. Location:/system/frameworks/base/libs/binder/Parcel. cpp

status_t Parcel::writeInt32(int32_t val){    return writeAligned(val);}template
 
  status_t Parcel::writeAligned(T val) {    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));    if ((mDataPos+sizeof(val)) <= mDataCapacity) {restart_write:        *reinterpret_cast
  
   (mData+mDataPos) = val;        return finishWrite(sizeof(val));    }    status_t err = growData(sizeof(val));    if (err == NO_ERROR) goto restart_write;    return err;}status_t Parcel::readInt32(int32_t *pArg) const{    return readAligned(pArg);}template
   
    status_t Parcel::readAligned(T *pArg) const {    COMPILE_TIME_ASSERT_FUNCTION_SCOPE(PAD_SIZE(sizeof(T)) == sizeof(T));    if ((mDataPos+sizeof(T)) <= mDataSize) {        const void* data = mData+mDataPos;        mDataPos += sizeof(T);        *pArg =  *reinterpret_cast
    
     (data);        return NO_ERROR;    } else {        return NOT_ENOUGH_DATA;    }}
    
   
  
 

The following 4 points are taken from exploring the Parcel mechanism in Android (I).
If you are interested, you can read it by yourself. It is not difficult to understand it. here we will summarize the basic ideas:
1. the entire read/write process is in the memory, mainly through memory operations such as malloc (), realloc (), memcpy (), so the efficiency is much higher than that of using external memory in JAVA serialization;
2. The read and write operations are 4-byte aligned. You can see # define PAD_SIZE (s) + 3 )&~ 3) This macro definition is to do this;
3. If the pre-allocated space is insufficient, newSize = (mDataSize + len) * 3)/2; 50% is allocated at a time;

4. For common data, the mData memory address is used. For IBinder-type data and FileDescriptor, The mObjects memory address is used. The latter is implemented through flatten_binder () and unflatten_binder (). The purpose is that the object read during deserialization is the original object instead of a new object.

 

VII. serialization and deserialization of Parcelable experiment? 1. Do any entity classes need to re-write the Parcelable interface?
2. If a new attribute is added to the subclass, do I need to write the writeToParcel and CREATOR of the parent class again?
3. Can the read/write sequence of variables be different between writeToParcel and createFromParcel?
4. Read and Write Parcelable objects (write operation dest. writeParcelable (obj, flags); read operation in. readParcelable (ObjectA. class. getClassLoader ());)
5. Read and Write Parcelable object arrays
dest.writeParcelableArray(mClassNameList.toArray(new ClassName[mClassNameList.size()]), flags);Parcelable[] parcelableArr = in.readParcelableArray(ClassName.class.getClassLoader());ArrayList
 
   arrayList = new ArrayList
  
   ();for (Parcelable object : parcelableArr) {     arrayList.add((ClassName)object);}
  
 


8. Self-implemented sequence and deserialization mechanism-data serialization in C language (idea of implementing serialization Mechanism in C language)



 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.