generics - Dagger 2 Generic Type 类注入(inject)错误

标签 generics dependency-injection dagger

我不能让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/

相关文章:

asp.net - 依赖注入(inject)和 ASP.net MVC 5/Web API 2

将 Angular 依赖注入(inject)到导出函数中

android - 无法解析 Dagger 的导入语句

android - : Ldagger/internal/Preconditions 解析失败

java - 如何编写加法的通用方法

swift - 是否可以将范围作为 Swift 字典中的键?

java - 使用泛型/继承组合不同类型的命令接口(interface)

java - Groovy 编译期间出现 StackOverflowError

javascript - Angular2 中没有服务提供者错误,为什么我需要将其注入(inject)到它的父组件中?

java - Dagger2 Maven : Missing POM for com. google.devtools.ksp:symbol-processing-api:jar:1