dagger cannot inject type parameter field

送分小仙女□ 提交于 2019-12-05 04:07:30
gk5885

As of the 2.0.1 release, Dagger 2 does support the type of injection that you're talking about. Take a look at GenericTest for all of the various permutations.

I had the same problem and got around it by adding a non-parameterized inner class and injecting into that. Then using a getter to get the injected class out.

It looks like this:

public class MainClass<T>{

   UtilityClass utility;

   public MainClass(){
       utility = new InjectorHelper().getHelper();
   }

   ...

   public static class InjectorHelper{

       @Inject
       UtilityClass utilityClass;

       public InjectorHelper(){
           Injector.getInstance().getAppComponent().inject(this);
       }

       public UtilityClass getUtilityClass(){
           return utilityClass
       }
   }
}

I also could not get it work either and I think it's against the design philosophy of dagger, which is to generate code that is exactly what a developer would also write.

In this case, it generates an injection adapter for the abstract class and another one for concrete class. With generic arguments to the abstract class, you essentially have to inject the fields from the abstract class in each concrete class injector.

If it wasn't an android object (which the android runtime creates), I'd suggest to pass the service in the call to the super constructor.

In this case, I'd suggest to inject the service in the concrete classes and to provide it using an abstract method:

protected abstract S getService();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!