【问题标题】:Android: error: non-static type variable T cannot be referenced from a static contextAndroid:错误:不能从静态上下文引用非静态类型变量 T
【发布时间】:2020-12-22 10:25:46
【问题描述】:

我有以下课程:

@Parcelize
data class Collection<T : Parcelable> constructor(
    var models: List<T>,
    var cursor: String?
) : Parcelable

当我使用Kotlin 1.4.10时,项目构建正确,没有任何错误,然后我将项目更新为Kotlin 1.4.21,并迁移到使用kotlin-parcelize而不是kotlin-android-extensions,所以在Kotlin更新之后,在构建项目我收到以下错误:

> Task :domain:kaptDebugKotlin FAILED
/Library/DevelopmentArea/workspace/baaz_android_new/clean_domain/domain/build/tmp/kapt3/stubs/debug/com/myapp/domain/model/Collection.java:101: error: non-static type variable T cannot be referenced from a static context
        public final com.myapp.domain.model.Collection<T>[] newArray(int size) {
                                                                   ^/Library/DevelopmentArea/workspace/baaz_android_new/clean_domain/domain/build/tmp/kapt3/stubs/debug/com/myapp/domain/model/Collection.java:110: error: non-static type variable T cannot be referenced from a static context
        public final com.myapp.domain.model.Collection<T> createFromParcel(@org.jetbrains.annotations.NotNull()

注意:我使用的是 Android Studio 4.1.1

【问题讨论】:

  • 想必你要找的答案在here
  • 这能回答你的问题吗? Migrate to the new kotlin-parcelize
  • 在实现同一个接口时不能将接口用作泛型,而是最好使用实现 Parcelable 的列表类型
  • 它已在 Kotlin 1.5.0 中修复。在 Android Studio 4.2.1 中使用 Kotlin 插件 1.5.0 测试。

标签: android kotlin parcelable kotlin-android-extensions


【解决方案1】:

目前为了修复我得到的错误,同时继续使用 Kotlin 1.4.21,我刚刚从任何具有问题中的泛型类型用法的类中删除了 @Parcelize 注释,并且刚刚实现了 @ 987654322@ 旧方式如下:

    data class Collection<T> constructor(
    var models: List<T>,
    var cursor: String?
) : Parcelable {

    constructor(parcel: Parcel) : this(
        mutableListOf<T>().also { list: List<T> ->
            parcel.readList(list, Collection<T>::models.javaClass.classLoader)
        },
        parcel.readString())

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeList(models)
        parcel.writeString(cursor)
    }

    override fun describeContents(): Int = 0

    companion object {

        @JvmField
        val CREATOR = object : Parcelable.Creator<Collection<Parcelable>> {
            override fun createFromParcel(source: Parcel): Collection<Parcelable> {
                return Collection(source)
            }

            override fun newArray(size: Int): Array<Collection<Parcelable>?> {
                return arrayOfNulls(size)
            }
        }
    }
}

【讨论】:

  • 现在将Caused by android.os.BadParcelableException: ClassNotFoundException when unmarshalling: 扔到readList 行,有什么想法吗?
猜你喜欢
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 2011-11-30
相关资源
最近更新 更多