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。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值