Kotlin用@Parcelize实现序列化Parcelable

藏宝库编辑 2024-9-24 23:41:52 17 0 来自 中国
简介

在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.Parcelable的writeToParcel(), describeContents() 等方法,还有天生一个构建器CREATOR。肯定要留意的是,这个注解仅仅在直接或间接实现了android.os.Parcelable的类才气使用,而且原始的构造属性才会被序列化。
使用

界说一个class为kotlin/Test.kt
@Parcelizedata class Test(        val name:String,        val id:Int)arcelable通过Tools->Kotlin->Show Bytecoded->Decompile得到test.decompiled.java
@Parcelizepublic 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。
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 19:26, Processed in 0.205954 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表