簡介
在Android項(xiàng)目中經(jīng)常要對(duì)Bean進(jìn)行Parcelable序列化
僵刮,也有很多序列化工具振乏。Android中提倡通過實(shí)現(xiàn)Parcelable
來對(duì)對(duì)象序列化瞻坝,但是如果是使用Java開發(fā)實(shí)現(xiàn)起來就比較繁瑣暮蹂,而Kotlin提供了@Parcelize
怨愤,可以輕松實(shí)現(xiàn)對(duì)Bean的序列化及反序列話派敷。先看看官方對(duì)@Parcelize
的解析:
/**
* Instructs the Kotlin compiler to generate `writeToParcel()`, `describeContents()` [android.os.Parcelable] methods,
* as well as a `CREATOR` factory class automatically.
*
* The annotation is applicable only to classes that implements [android.os.Parcelable] (directly or indirectly).
* Note that only the primary constructor properties will be serialized.
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
annotation class Parcelize
意思是,這個(gè)注解告訴Kotlin 編譯器要自動(dòng)生成android.os.Parcelable
的writeToParcel()
, describeContents()
等方法撰洗,還有生成一個(gè)構(gòu)建器CREATOR
篮愉。一定要注意的是,這個(gè)注解僅僅在直接或間接實(shí)現(xiàn)了android.os.Parcelable
的類才能使用差导,并且原始的構(gòu)造屬性才會(huì)被序列化试躏。
使用
定義一個(gè)class為kotlin/Test.kt
@Parcelize
data class Test(
val name:String,
val id:Int
):Parcelable
通過Tools->Kotlin->Show Bytecoded->Decompile得到test.decompiled.java
@Parcelize
public final class Test implements Parcelable {
@NotNull
private final String name;
private final int id;
public static final android.os.Parcelable.Creator CREATOR = new Test.Creator();
···
public Test(@NotNull String name, int id) {
Intrinsics.checkNotNullParameter(name, "name");
super();
this.name = name;
this.id = id;
}
···
public void writeToParcel(@NotNull Parcel parcel, int flags) {
Intrinsics.checkNotNullParameter(parcel, "parcel");
parcel.writeString(this.name);
parcel.writeInt(this.id);
}
static {
CREATOR = new Test.Creator();
}
public static class Creator implements android.os.Parcelable.Creator {
@NotNull
public final Test[] newArray(int size) {
return new Test[size];
}
public Object[] newArray(int var1) {
return this.newArray(var1);
}
@NotNull
public final Test createFromParcel(@NotNull Parcel in) {
Intrinsics.checkNotNullParameter(in, "in");
return new Test(in.readString(), in.readInt());
}
public Object createFromParcel(Parcel var1) {
return this.createFromParcel(var1);
}
}
}
可以看到生成的java對(duì)應(yīng)也生成了writeToParcel()
, describeContents()
和一個(gè)構(gòu)建器CREATOR
。
總結(jié)
@Parcelize告訴Koltin幫自動(dòng)實(shí)現(xiàn)Parcelable接口设褐,到底還是我們熟悉的Parcelable颠蕴。