TOP

android对象序列化Parcelable浅析(二)
2017-10-12 10:09:39 】 浏览:3370
Tags:android 对象 序列化 Parcelable 浅析

omParcel(this); 19 } 20 21 /** @hide */ 22 public final <T extends Parcelable> Parcelable.Creator<T> readParcelableCreator( 23 ClassLoader loader) { 24 String name = readString(); //此处获得类名,还不太清楚如何获得的,如果想深入学习可以再研究 25 if (name == null) { 26 return null; 27 } 28 Parcelable.Creator<T> creator; 29 synchronized (mCreators) { 30 HashMap<String,Parcelable.Creator> map = mCreators.get(loader); 31 if (map == null) { 32 map = new HashMap<String,Parcelable.Creator>(); 33 mCreators.put(loader, map); 34 } 35 creator = map.get(name); 36 if (creator == null) { 37 try { 38 Class c = loader == null ? 39 Class.forName(name) : Class.forName(name, true, loader); 40 Field f = c.getField("CREATOR"); 41 creator = (Parcelable.Creator)f.get(null); 42 } 43 catch (IllegalAccessException e) { 44 Log.e(TAG, "Illegal access when unmarshalling: " 45 + name, e); 46 throw new BadParcelableException( 47 "IllegalAccessException when unmarshalling: " + name); 48 } 49 catch (ClassNotFoundException e) { 50 Log.e(TAG, "Class not found when unmarshalling: " 51 + name, e); 52 throw new BadParcelableException( 53 "ClassNotFoundException when unmarshalling: " + name); 54 } 55 catch (ClassCastException e) { 56 throw new BadParcelableException("Parcelable protocol requires a " 57 + "Parcelable.Creator object called " 58 + " CREATOR on class " + name); 59 } 60 catch (NoSuchFieldException e) { 61 throw new BadParcelableException("Parcelable protocol requires a " 62 + "Parcelable.Creator object called " 63 + " CREATOR on class " + name); 64 } 65 catch (NullPointerException e) { 66 throw new BadParcelableException("Parcelable protocol requires " 67 + "the CREATOR object to be static on class " + name); 68 } 69 if (creator == null) { 70 throw new BadParcelableException("Parcelable protocol requires a " 71 + "Parcelable.Creator object called " 72 + " CREATOR on class " + name); 73 } 74 75 map.put(name, creator); 76 } 77 } 78 79 return creator; 80 }

重点看粗体部分的代码——真想大白:

在接收端收到parcel之后,解析的时候,会通过反射去获取对象的Creator,然后保存到一个hashmap中。然后调用Creator的createFromParcel方法来实现解包。

 

反射在源码中也是无处不在!

 

请关注公众号获取更多资料


android对象序列化Parcelable浅析(二) https://www.cppentry.com/bencandy.php?fid=98&id=144787

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android笔记——Android中数据的.. 下一篇Android自定义控件之轮播图控件