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方法来实现解包。
反射在源码中也是无处不在!
|