gpt4 book ai didi

Android - 运行时 Dagger 注入(inject)

转载 作者:行者123 更新时间:2023-11-29 18:32:35 25 4
gpt4 key购买 nike

我需要在运行时使用 Dagger 注入(inject)类。我的问题是在方法中本地注入(inject)类时出现编译时错误,而且我无法在运行时注入(inject)而不使用 @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()
}
}

在 Dagger 实现中我会这样做

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

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

对于如何在运行时注入(inject)它有什么帮助吗?

最佳答案

你不能在运行时注释某些东西,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
}
}

关于Android - 运行时 Dagger 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55593294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com