美文网首页kotlin
Kotlin用@Parcelize实现序列化Parcelable

Kotlin用@Parcelize实现序列化Parcelable

作者: hao_developer | 来源:发表于2022-06-07 09:43 被阅读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.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。

    相关文章

      网友评论

        本文标题:Kotlin用@Parcelize实现序列化Parcelable

        本文链接:https://www.haomeiwen.com/subject/hfzsmrtx.html