我不能让MyClass
由于其通用性质,此处被注入(inject)。
Dagger 提示这个错误:
Error:(187, 10) error: com.test.MyClass has type parameters, cannot members inject the raw type. via: com.test.MyComponent.inject(com.test.MyClass obj) [component injection method for type: com.test.MyClass]
我用谷歌搜索了一下,但无法找到这种情况的解决方案。
class MyClass<Type> {
@Inject
UserCredentials userCredentials;
ResultProducer<Type> mRP;
public MyClass(ResultProducer<Type> resultProd) {
mRP = resultProd;
Injector.getComponent().inject(this);
}
public Type getResult() {
if (userCredentials.isLoggedIn()) {
mRP.get();
} else {
mRP.getAnonymousCache();
}
}
}
@Component(modules = CredentialsModule.class )
interface MyComponent {
void inject(MyClass obj);
}
@Module
class CredentialsModule {
@Provides
public UserCredentials provideUserCredentials() {
return new UserCredentials();
}
}
最佳答案
我解决了这个问题有点不同,就像这样(我们还有 5 年,所以它在 Kotlin 中,但我猜 Java 也可以):
// The class I want to inject, multiple generics
class SomeDataStorage<K, V> {
@Inject
lateinit var theDependencyINeed: TheDependencyINeed
init {
ComponentSingleton.getSomeComponent().inject(this as SomeDataStorage<Any, Any>)
}
fun getValue(key: K): V {
return theDependencyINeed.doSomeStuff() as V
}
}
// Component
interface MyComponent {
fun inject(someDataStorage: SomeDataStorage<Any, Any>)
}
诀窍是获取您允许的泛型的一些共同父级(在我的情况下,我不在乎,所以我只做任何,这就是一切)并使用它。需要一些未经检查的类型转换,但没关系。
关于generics - Dagger 2 Generic Type 类注入(inject)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32498912/