Generic @Inject'd fields in an abstract superclass

后端 未结 2 895
花落未央
花落未央 2021-02-05 05:49

Consider a MVP-ish set of types. An abstract Presenter exists, with a View interface:

public interface View {
    //...
}

public abstract class AbstractPresente         


        
相关标签:
2条回答
  • 2021-02-05 06:15

    That looks like a bug as it shouldn't throw an exception, but it should log a warning explaining that type parameters need to be bound to a specific type.

    The rest is for Dagger2, and I'm using 2.1-SNAPSHOT. You haven't provided an example @Component that will do the injection and without it Dagger2 2.1-SNAPSHOT doesn't actually report a problem. It's possible that it has already fixed your problem and I'm seeing a slightly different version but if not then I presume your component looks something like this:

    @Component
    public interface PresenterComponent {
      <V extends View> void inject(AbstractPresenter<V> presenter);
    }
    

    When Dagger2 is processing this it cannot determine a concrete type for V, and so it doesn't know what type to insert. It can't just insert say LoginView because that would break if it was passed a AbstractPresenter<LogoutView>.

    However, if you use say the following then Dagger2 can determine that it needs to inject a LoginView into AbstractPresenter<LoginView> and will do so safely.

    @Module
    public class LoginModule {
      @Provides LoginView provideLoginView() {
        return new LoginViewImpl();
      }
    }
    
    @Component(modules = LoginModule.class)
    public interface LoginComponent {
        void inject(LoginPresenter presenter);
    }
    

    Unless you have no control over when an object is created, e.g. if some framework creates it for you and then passes in for you to initialize, it is much better to use @Inject on the constructor if you can, e.g. like this:

    public LoginPresenter extends AbstractPresenter<LoginView> {
        //...
        @Inject LoginPresenter(LoginView view) {
            super(view);
        //...
        }
    }
    
    0 讨论(0)
  • 2021-02-05 06:30

    This is because of the Type arguments. Injects does not work when u have a type arguments. U need to do something like this,

    bind(new LoginPresenter<LoginViewImpl>(){});
    
    0 讨论(0)
提交回复
热议问题