当前位置:
首页
文章
移动端
详情

Kotlin用@Parcelize实现序列化Parcelable

简介

在Android项目中经常要对Bean进行Parcelable序列化,也有很多序列化工具。Android中提倡通过实现Parcelable来对对象序列化,但是如果是使用Java开发实现起来就比较繁琐,而Kotlin提供了@Parcelize,可以轻松实现对Bean的序列化及反序列话。先看看官方对@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

意思是,这个注解告诉Kotlin 编译器要自动生成android.os.ParcelablewriteToParcel(), describeContents() 等方法,还有生成一个构建器CREATOR。一定要注意的是,这个注解仅仅在直接或间接实现了android.os.Parcelable的类才能使用,并且原始的构造属性才会被序列化。

使用

定义一个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对应也生成了writeToParcel(), describeContents() 和一个构建器CREATOR

总结

@Parcelize告诉Koltin帮自动实现Parcelable接口,到底还是我们熟悉的Parcelable。

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。