Android - 运行时 Dagger 注入
Android - Dagger injection at runtime
我需要在运行时使用匕首注入 class。我的问题是在方法中本地注入 class 时出现编译时错误,而且我无法在运行时注入而不使用 @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
关于如何在运行时注入这个的任何帮助?
你不能在运行时注释某些东西,the element value in Java annotation has to be a constant expression。
但是这个用例可以通过map multibind解决。
在你的Module
中,除了@Bind
或@Provide
之外,还用@IntoMap
和地图键注释了抽象的乐趣(抱歉有任何错误我的科特林)
@Binds
@IntoMap
@StringKey("p1")
abstract fun bindP1Class(p1: P1): PerformActionInterface
@Binds
@IntoMap
@StringKey("p2")
abstract fun bindP2Class(p2: P2): PerformActionInterface
然后在你的 PerformAction
class 中,声明从 String
到 PerformActionInterface
的映射的依赖项,然后对映射做任何操作:
// 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
}
}
我需要在运行时使用匕首注入 class。我的问题是在方法中本地注入 class 时出现编译时错误,而且我无法在运行时注入而不使用 @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
关于如何在运行时注入这个的任何帮助?
你不能在运行时注释某些东西,the element value in Java annotation has to be a constant expression。
但是这个用例可以通过map multibind解决。
在你的Module
中,除了@Bind
或@Provide
之外,还用@IntoMap
和地图键注释了抽象的乐趣(抱歉有任何错误我的科特林)
@Binds
@IntoMap
@StringKey("p1")
abstract fun bindP1Class(p1: P1): PerformActionInterface
@Binds
@IntoMap
@StringKey("p2")
abstract fun bindP2Class(p2: P2): PerformActionInterface
然后在你的 PerformAction
class 中,声明从 String
到 PerformActionInterface
的映射的依赖项,然后对映射做任何操作:
// 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
}
}