Android - 运行时Dagger注入

问题描述 投票:0回答:1

我需要在运行时使用dagger注入类。我的问题是在方法中本地注入类时出现编译时错误,并且我无法在运行时注入而不使用@Named的常量

interface PerformActionInterface{
      fun performAction()
}

class P1 : PerformActionInterface{
   override fun performAction(){
   }
}

class P2 : PerformActionInterface{
   override fun performAction(){
   }
}


class PerformAction @Inject constructor(){

      fun perform(name : String){

        @Inject
        @Named(name)
        performActionInterface : PerformActionInterface

        performActionInterface.performAction()
    }
}

像匕首一样,我会这样做

 @Binds
 @Named("p1")
 abstract bindP1Class(p1 : P1) :PerformActionInterface

 @Binds
 @Named("p2")
 abstract bindP1Class(p2 : P2) :PerformActionInterface

有关如何在运行时注入此内容的任何帮助吗?

android kotlin dagger-2 dagger
1个回答
2
投票

你不能在运行时注释一些东西,the element value in Java annotation has to be a constant expression

但是这个用例可以通过map multibind来解决。

在你的Module中,除了@Bind@Provide之外,还用@IntoMap和地图键注释抽象乐趣(抱歉我的Kotlin中有任何错误)

@Binds
@IntoMap
@StringKey("p1")
abstract fun bindP1Class(p1: P1): PerformActionInterface

@Binds
@IntoMap
@StringKey("p2")
abstract fun bindP2Class(p2: P2): PerformActionInterface

然后在你的PerformAction类中,声明一个地图从StringPerformActionInterface的依赖关系,并对地图做任何事情:

// map value type can be Lazy<> or Provider<> as needed
class PerformAction @Inject constructor(
        val map: Map<String, @JvmSuppressWildcards PerformActionInterface>) {

    fun perform(name: String) {
        map.get(name)?.performAction()
        // or do something if the get returns null
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.