与kotlin一起,拥有一个Data
类可以实现Parcelable
似乎在同伴中有两种定义CREATOR: Parcelable
的方式:
data class Data (
@SerializedName("id")
val id: String?,
@SerializedName("blob")
val blob: String?
) : Parcelable {
... ...
companion object CREATOR : Parcelable.Creator<Data> {
override fun createFromParcel(parcel: Parcel): Data {
return Data(parcel)
}
override fun newArray(size: Int): Array<Data?> {
return arrayOfNulls(size)
}
}
}
data class Data (
@SerializedName("id")
val id: String?,
@SerializedName("blob")
val blob: String?
) : Parcelable {
... ...
companion object {
@JvmField val CREATOR: Parcelable.Creator<Data> = object : Parcelable.Creator<Data> {
override fun createFromParcel(parcel: Parcel): Data {
return Data(parcel)
}
override fun newArray(size: Int): Array<Data?> {
return arrayOfNulls(size)
}
}
}
}
相应的Java反编译代码为
@JvmField
@NotNull
public static final Creator CREATOR = (Creator)(new Creator() {
@NotNull
public Data createFromParcel(@NotNull Parcel parcel) {
Intrinsics.checkParameterIsNotNull(parcel, "parcel");
return new Data(parcel, (DefaultConstructorMarker)null);
}
// $FF: synthetic method
// $FF: bridge method
public Object createFromParcel(Parcel var1) {
return this.createFromParcel(var1);
}
@NotNull
public Data[] newArray(int size) {
return new Data[size];
}
// $FF: synthetic method
// $FF: bridge method
public Object[] newArray(int var1) {
return this.newArray(var1);
}
});
public static final Data.CREATOR CREATOR = new Data.CREATOR((DefaultConstructorMarker)null);
public static final class CREATOR implements Creator {
@NotNull
public Data createFromParcel(@NotNull Parcel parcel) {
Intrinsics.checkParameterIsNotNull(parcel, "parcel");
return new Data(parcel);
}
// $FF: synthetic method
// $FF: bridge method
public Object createFromParcel(Parcel var1) {
return this.createFromParcel(var1);
}
@NotNull
public Data[] newArray(int size) {
return new Data[size];
}
// $FF: synthetic method
// $FF: bridge method
public Object[] newArray(int var1) {
return this.newArray(var1);
}
private CREATOR() {
}
// $FF: synthetic method
public CREATOR(DefaultConstructorMarker $constructor_marker) {
this();
}
}
并使用kotlin从包裹中获取List<Data>
:
parcel.createTypedArrayList(Data.CREATOR)
在Java中可能是:
List list = (List)(new ArrayList());
parcel.readTypedList(list, (Creator)Data.CREATOR);
kotlin中的两个CREATOR都很好。
有什么区别,哪个更好用?