Android Dagger Dependency Injection fails on private Fields

纵饮孤独 提交于 2019-12-04 22:53:16

Making a private field 'package visible' may not always be what you want. The Dagger documentation suggests the following:

Injecting final fields and private members. For best performance Dagger generates code. Work around this by using constructor injection.

Here's an example:

private ItemFactoryImpl itemFactory;
private BuildingFactory buildingFactory;

@Inject
public World(ItemFactoryImpl itemFactory, BuildingFactory buildingFactory) {
    this.itemFactory = itemFactory;
    this.buildingFactory = buildingFactory;
}

Dagger cannot support private fields and still support code-generated adapters (to avoid reflection). The way systems like Guice support private fields is they change the access to the field reflectively before accessing them. Since dagger generates an InjectAdapter in the same package as the class to be injected, it can access package-friendly, protected, or public fields. It cannot access private fields.

One of Dagger's advantages IS that it avoids reflection, so using reflection to bypass field visibility is not a desirable feature.

Just the remove the private to set the visibility of your field to package friendly.

Dagger doesn't support injection on private fields.

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