美文网首页
序列化,Serializable和parceable区别

序列化,Serializable和parceable区别

作者: 竖起大拇指 | 来源:发表于2020-07-17 11:22 被阅读0次

序列化

序列化是一种用来处理对象流的机制。
所谓对象流:就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。
序列化:把java对象转换为字节序列的过程
反序列化:把字节序列恢复为java对象的过程
Java序列化机制是通过运行时判断类的序列号ID(SerialVersionUID)来判定版本的一致性。
在反序列化时,java虚拟机会通过二进制流中的SerialVersionUID与本地的对应的实体类进行比较,如果相同就认为是一致的,可以进行反序列化,正确获得信息,否则抛出序列化版本不一致的异常。
Seralizable无法序列化静态变量,使用transient修饰的对象也无法序列化。
当一个父类实现序列化,子类自动实现序列化,不需要再显示实现Serializable接口。

区别

1.Serializable是属于Java自带的,本质是使用了反射。序列化的过程比较慢,这种机制在序列化的时候会创建很多临时的对象,比引起频繁的GC。
2.Parcelable是安卓特有的序列化API,它的出现是为了解决Serializable序列化的过程中消耗资源严重的问题。实现原理是在内存中建立一块共享数据块,序列化和反序列化均是操作这一块的数据。
3.如果在内存中使用建议Parcelable。持久化操作建议使用Serializable。另外Parcelable的读写顺序必须一致

Parcelable的三个过程:序列化,反序列化和描叙

1.序列化:

/**
     * Flatten this object in to a Parcel.
     * 
     * @param dest The Parcel in which the object should be written.
     * @param flags Additional flags about how the object should be written.
     * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
     */
    public void writeToParcel(Parcel dest, @WriteFlags int flags);

2.反序列化

/**
     * Interface that must be implemented and provided as a public CREATOR
     * field that generates instances of your Parcelable class from a Parcel.
     */
    public interface Creator<T> {
        /**
         * Create a new instance of the Parcelable class, instantiating it
         * from the given Parcel whose data had previously been written by
         * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
         * 
         * @param source The Parcel to read the object's data from.
         * @return Returns a new instance of the Parcelable class.
         */
        public T createFromParcel(Parcel source);
        
        /**
         * Create a new array of the Parcelable class.
         * 
         * @param size Size of the array.
         * @return Returns an array of the Parcelable class, with every entry
         * initialized to null.
         */
        public T[] newArray(int size);
    }

3.描述

 /**
     * Describe the kinds of special objects contained in this Parcelable
     * instance's marshaled representation. For example, if the object will
     * include a file descriptor in the output of {@link #writeToParcel(Parcel, int)},
     * the return value of this method must include the
     * {@link #CONTENTS_FILE_DESCRIPTOR} bit.
     *  
     * @return a bitmask indicating the set of special object types marshaled
     * by this Parcelable object instance.
     */
    public @ContentsFlags int describeContents();
    

相关文章

网友评论

      本文标题:序列化,Serializable和parceable区别

      本文链接:https://www.haomeiwen.com/subject/yrawhktx.html