gpt4 book ai didi

java - Dagger 错误 : Can't inject a non-static inner class

转载 作者:行者123 更新时间:2023-11-30 08:58:44 25 4
gpt4 key购买 nike

我正在尝试使用 Dagger 在我的应用程序中实现依赖项注入(inject)。我的结构与 "Simpler Android apps with Flow and Mortar" 中描述的类似

我有一个 DayScreen 类:

@Layout(R.layout.day)
public class DayScreen extends DateScreen {
LocalDate date;

public DayScreen(LocalDate date) { this.date = date; }

@Override public String getMortarScopeName() { return getClass.getName(); }
@Override public Object getDaggerModule getModule() { retrun new Module(); }

@dagger.Module(addsTo = UiModule.class, injects = DayView.class, complete = false, library = true)
public class Module {
@Inject RestService api;
@Inject DateTimeFormatter formatter;

@Provides @Named("DayScreenDate") LocalDate provideDate(){
return date;
}
}

@Singleton
public class Presenter extends ViewPresenter<DayView> {
//@Inject RestService api;
//@Inject DateTimeFormatter formatter;
RestService api;
DateTimeFormatter formatter;

@Inject Presenter( RestService api, DateTimeFormatter formatter){
this.api = api;
this.formatter = formatter;
}

@Override
protected void onLoad(Bundle savedInstanceState) {
super.onLoad(savedInstanceState);
api.statisticsDay(DayScreen.this.date.format(formatter))
.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(
resp -> getView().setData(resp.events),
err -> Log.e(TAG, err.getLocalizedMessage()),
() -> Log.v(TAG, "day stats received")
);
}
}

这里 DateScreen 是一个抽象:

public abstract class DateScreen implements Blueprint {
protected LocalDate date;

public DateScreen() { this(LocalDate.now()); }
public DateScreen(LocalDate date) { this.date = date; }

public LocalDate getDate() { return date; }
public void setDate(LocalDate date){ this.date = date; }
}

我试图通过构造函数和槽字段注入(inject)在 Module 和 Presenter 中注入(inject) apiformatter 但它咳嗽了同样的错误 error: Can't inject一个非静态内部类:...

有人知道为什么它需要静态类吗?是否有任何更改使我上面提到的文章变得无关紧要?

谢谢。

最佳答案

非静态类需要一个封闭的实例来实例化。这会阻止 DI 框架实例化它们。如果您有嵌套类,那么在任何情况下都将它们设为静态是个好主意。

如果您的嵌套类本质上依赖于封闭类实例,那么您必须重构以使这些类成为静态类,并定义一个采用封闭类实例的显式构造函数。

关于java - Dagger 错误 : Can't inject a non-static inner class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27506715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com