Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting generic class with Dagger

I have an abstract base class in my project

public abstract class BaseActivity<T extends BasePresenter<? extends IBaseView>> implements IBaseView{

Into which I try to inject a generic class like this:

@Inject protected T mPresenter; 

Is there any way to make dagger work with such a generic injection? Dagger generates code like:

public final class BaseActivity$$InjectAdapter extends Binding<BaseActivity>
implements MembersInjector<BaseActivity> {
    private Binding<T> mPresenter;
}

And then fails because "T cannot be resolved to a type". Is there any way to make it generate a

Binding<SomethingExtendingBasePresenter> mPresenter

in such case?

like image 855
Malthan Avatar asked Oct 16 '13 17:10

Malthan


People also ask

What is Dagger dependency injection?

Dagger is a fully static, compile-time dependency injection framework for Java, Kotlin, and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.

Why to use Dagger in Android?

Dagger automatically generates code that mimics the code you would otherwise have hand-written. Because the code is generated at compile time, it's traceable and more performant than other reflection-based solutions such as Guice. Note: Use Hilt for dependency injection on Android.


1 Answers

The only way I know of is to create a new class that extends your generic. One for each type you are interested in.

public class Foo extends BaseActivity<SomethingExtendingBasePresenter> {
}

@Inject
Foo mFoo;
like image 61
Android Developer Avatar answered Oct 13 '22 18:10

Android Developer