Dagger 2 Generic Type class inject error

Andrea Baccega picture Andrea Baccega · Sep 10, 2015 · Viewed 18.1k times · Source

I'm not able to let MyClass here being injected due to its Generic nature.

Dagger complains with this error:

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]

I googled a bit but was unable to find a solution to this case scenario.

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();
    }
}

Answer

lobzik picture lobzik · Oct 21, 2015

I have run into the same issue and found this article.

In a nutshell you have this options:

  1. Make not generic wrapper class containing injected fields, make it to be a field of your class and inject it instead of generic class itself.
  2. Inject child non-generic class instead of base class. All annotated with @Inject fields of base class will be also injected, but they have to be public/protected that is not good.
  3. Make annotated with @Inject setter in the base class and private field. Injecting child non-generic class will lead to triggering the setter with parameter got from the object graph.