Parcelable和Serializable的区别

    xiaoxiao2021-03-25  69

    我们知道andriod在本地存储对象或者用intent传递对象的时候,需要把对象序列化才能够对其进行操作,在java中我们所熟悉的是对象实现serializable接口即可,而在andriod中官方推荐使用的是Parcelable接口,两者有什么区别呢? 1.Serializable是java中的序列化接口,使用简单但是开销比较大,序列化合反序列化需要大量的I/O操作。 2.Parcelable是andriod中的序列化方式,因此有更适合andriod平台的有点是序列化合反序列化的效率高,但是其缺点就是使用起来比较麻烦,使用过Parcelable接口的同学应该知道实现Parcelable接口需要有序列化,反序列化,内容描述符这几个过程。 1).序列化由writeToParcel方法来完成,最终通过Parcel中的恶意系列write方法来完成的。 2).反序列化功能则由CREATOR来完成,其内部标明了如何创建序列化对象和数组,并通过Parcel的一系列read方法来完成反序列化过程;内容描述符功能有describeCoontnets方法来完成,几乎在所有情况下这个方法东应该返回0,仅当当前对象中存在文件描述符时,返回1。另外需要注意的是,在序列化对象的类里面如果其它可序列化对象,则序列化过程需要传递当前县城的上下文类加载器,否则汇报无法找到类的错误。 3).举个栗子: public class Man implements Parcelable{ public int userId; public String userName; public boolean isMale; public Dog dog; public User(int userId,String userName,boolean isGood){ this.userId=userId; this.userName=userName; this.isMale=isMale; } public int describeContents(){ return 0; } public void writeToParcel(Parcel out,int flags){ out.writeInt(userId); out.writeString (userName); out.writeInt(isMale?1:0); out.writeparcelable(dog,0); } public static final Parcelable.Creator<Man> CREATOR=new Parcelable.Creator<Man>(){ public User createFromParcel(Parcel in){ return new Man(in); } public Man[] newArray(int size){ return new Man[size]; } }; private Man(Parcel in){ userId=in.readInt(); userName=in.readString(); isMale=in.readInt()==1; book=in.readParcelable(Thrad.currentThread().getContextClassLoader()); } }参考资料:Andriod 开发艺术探索
    转载请注明原文地址: https://ju.6miu.com/read-39269.html

    最新回复(0)