本文介绍了lateinit的isInitialized属性在伴侣对象中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例类,我已经用java的方式实现了它:

I have a singleton class which i have implemented it in java fashion :

companion object {

    @Volatile private lateinit var instance: TrapBridge

    fun bridge(): TrapBridge {
        if (!this::instance.isInitialized) {
            synchronized(this) {
                if (!this::instance.isInitialized) {
                    instance = TrapBridge()
                }
            }
        }
        return instance
    }

}

现在的问题是我不能使用isInitialized属性,因为它引发了NoSuchFieldError异常:

now the problem is i can't use isInitialized property because it throws NoSuchFieldError exception :

java.lang.NoSuchFieldError: No field instance of type Lcom/sample/trap/model/TrapBridge; in class Lcom/sample/trap/model/TrapBridge$Companion; or its superclasses (declaration of 'com.sample.trap.model.TrapBridge$Companion' appears in /data/app/com.sample.trapsample-L9D8b2vxEQfiSg9Qep_eNw==/base.apk)

,我认为这是因为instance是类变量而不是实例变量,所以我无法使用this关键字引用它:/

and i think it's because instance is class variable and not instance variable so i can't reference it with this keyword :/

我也无法检查它是否为null,因为它会抛出UninitializedPropertyAccessException:

also i can't check if it's null because it throws UninitializedPropertyAccessException :

lateinit property instance has not been initialized

推荐答案

不幸的是,这是一个已知问题,已跟踪此处有关官方Kotlin问题跟踪器.

Unfortunately this is a known issue, tracked here on the official Kotlin issue tracker.

这篇关于lateinit的isInitialized属性在伴侣对象中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:02