继承和泛型以及Dagger2

时间:2018-02-09 20:33:30

标签: java android generics inheritance dagger-2

我有两种片段。其中一个是ListFragment,另一个是ListWithFilterFragment ListWithFilterFragment extend ListFragment。此外,我有两个ListWithFilterPresenter extend ListPresenter这些片段的演示者。所以我在演示者中定义了单独的模块,在Dagger中定义了单独的组件。我想为这些片段注入正确的演示者,但我收到了错误

这是ListFragment

public class ListFragment<V extends ListView> extends BaseFragment<V, ListPresenter<V>> implements ListView {
    @Inject
    ListPresenter presenter;

    @NonNull
    @Override
    public ListPresenter createPresenter() {
    DaggerListComponent.builder().build().inject((ListFragment<ListView>) this);
    return presenter;
}

这是ListWithFilterFragment

public class ListWithFilterFragment extends ListFragment<ListWithFilterView> implements ListWithFilterView {
    @Inject
    ListWithFilterPresenter presenter;

    @NonNull
    @Override
    public ListWithFilterPresenter createPresenter() {
        DaggerListWithFilterComponent.builder().build().inject(this);
        return presenter;
    }
}

这是ListComponent

@Singleton
@Component(modules = {ListPresenterModule.class, 
ListInteractorModule.class})
public interface ListComponent {
    void inject(ListFragment<ListView> fragment);
}

这是ListWithFilterComponent

@Singleton
@Component(modules = {ListWithFilterPresenterModule.class, 
ListInteractorModule.class})
public interface ListWithFilterComponent {
    void inject(ListWithFilterFragment fragment);
}

和我的演示者模块

@Module
public class ListWithFilterPresenterModule {
    @Provides @NonNull @Singleton
    public ListWithFilterPresenter providePresenter(ListInteractor interactor) {
        return new ListWithFilterPresenter(interactor);
    }
} 

@Module
public class ListPresenterModule {
    @Provides @NonNull @Singleton
    public ListPresenter providePresenter(ListInteractor interactor) {
        return new ListPresenter(interactor);
    }
}
  

错误:(16,10)错误:如果没有@ Provide-或@ Produces-annotated.method.com.sober.appModules.List.presenter.ListPresenter,则无法提供com.sober.appModules.List.presenter.ListPresenter被注入   com.sober.appModules.List.ui.ListFragment.presenter   com.sober.appModules.List.ui.ListWithFilterFragment注入com.sober.appModules.List.injection.ListWithFilterComponent.inject(fragment)

1 个答案:

答案 0 :(得分:1)

Dagger不做部分注射。它可以提供所有对象,也可能因无法提供而失败。

在您的情况下,ListWithFilterComponent无法向ListPresenter提供ListWithFilterFragment - 或者更确切地说是ListFragment父级。

在行尾看到评论

error: List.presenter.ListPresenter cannot be provided without an @Provides- or @Produces-annotated.method.
List.presenter.ListPresenter is injected at  <- missing object
List.ui.ListFragment.presenter <- field in parent that is getting injected
List.ui.ListWithFilterFragment is injected at <- object it tries to inject
List.injection.ListWithFilterComponent.inject(fragment) <- component that's missing something

如果您想保留当前的设置,您还需要提供ListPresenter的{​​{1}},否则您需要重构您的片段,以便他们不会延长另一个。