cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

在用kotlin和dagger2的時(shí)候,用到了Dagger 2 的 @Qualifier來指定對象

 class MainActivity : AppCompatActivity (){
    @Inject
    @Named("red")
    lateinit var cloth:Cloth
}
@Module
class MainModule {

    @Provides
    @Named("red")
    fun getRedCloth() : Cloth{
        var cloth = Cloth()
        cloth.color="紅色"

        return cloth;
    }
    @Provides
    @Named("blue")
    fun getBlueCloth() : Cloth{
        var cloth = Cloth()
        cloth.color="藍(lán)色"

        return cloth;
    }

結(jié)果報(bào)錯(cuò)了

cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

搜了半天,出現(xiàn)問題的原因是
變量cloth這行代碼編譯為 Java 字節(jié)碼的時(shí)候會(huì)對應(yīng)三個(gè)目標(biāo)元素,一個(gè)是變量本身、還有 getter 和 setter,Kotlin 不知道這個(gè)變量的注解應(yīng)該使用到那個(gè)目標(biāo)上。
要解決這個(gè)方式,需要使用 Kotlin 提供的注解目標(biāo)關(guān)鍵字來告訴 Kotlin 所注解的目標(biāo)是那個(gè),上面示例中需要注解應(yīng)用到 變量上,所以使用 field 關(guān)鍵字:

 class MainActivity : AppCompatActivity (){
    @Inject
    @field:Named("red")
    lateinit var cloth:Cloth
}

就好了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容