Android-在运行时注入Dagger

时间:2019-04-09 12:47:55

标签: android kotlin dagger-2 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

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

1 个答案:

答案 0 :(得分:1)

您无法在运行时注释the element value in Java annotation has to be a constant expression

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

在您的Module中,除了@Bind@Provide之外,还用@IntoMap和map键注释了抽象乐趣(对我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
    }
}