在Dagger中注入泛型

在Dagger中注入泛型

本文介绍了在Dagger中注入泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Dagger中是否可以执行以下操作:

Is it possible in Dagger to do something like the following:

public abstract class Presenter<T extends BaseView> {

    @Inject T mView;

    public void showLoadingIndicator() {
        mView.showLoading();
    }

}

(示例模块)

public class MyModule {
    private MyView mView; //extends BaseView

    public MyModule(MyView view) {
        mView = view;
    }

    @Provides
    public BaseView provideView() {
        return mView;
    }

}

然后使用上面的模块创建一个对象图,并将视图注入到演示者中?

And then create an object graph with the module above and inject the view into the presenter?

我的尝试没有成功(通常会出现未知类'T'"错误).我不确定我的配置是否错误或此功能不受支持.

My attempts have not worked (usually get "unknown class 'T'" sort of errors). I'm not sure if my configuration is wrong or if this is unsupported functionality.

推荐答案

有一个简单/明显的变通办法来实现相同的目标,具体取决于代码的其余部分.

There's a simple/obvious workaround to achieve the same thing, depending on what the rest of your code looks like.

通过不使用字段注入来初始化基本演示者的mView字段,您可以将其传递给构造函数,然后让Module提供它,例如:

By not using field injection to initialize the mView field of the base presenter, you could just pass it into the constructor, and let the Module provide it, like:

public abstract class Presenter<T extends BaseView> {
    private final T mView;

    public Presenter(T view) {
        mView = view;
    }

    public void showLoadingIndicator() {
        mView.showLoading();
    }
}

假设它是这样使用的:

public class MainPresenter extends Presenter<MainActivity> {
    public MainPresenter(MainActivity view) {
        super(view);
    }
}

,该模块创建演示者并将视图传递给它:

and the module creates the presenter and passes the view to it:

@Module(injects = MainActivity.class)
public class MainModule {
    private final MainActivity mMainActivity;

    public MainModule(MainActivity mainActivity) {
        mMainActivity = mainActivity;
    }

    @Provides
    MainPresenter mainPresenter() {
        return new MainPresenter(mMainActivity);
    }
}

无论如何,我还是更喜欢这种方式,因为我更喜欢构造函数注入而不是字段注入(除了不是由Dagger创建的对象,例如活动或片段级别,我们当然不能避免@Inject).

I prefer this anyway, because I prefer constructor injection over field injection (except on the objects not created by Dagger such as the activity or fragment level of course, where we can't avoid @Inject).

在此处编码

这篇关于在Dagger中注入泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:18