Android Dagger Dependency Injection fails on private Fields

前端 未结 3 1399
既然无缘
既然无缘 2020-12-18 19:29

I\'m new to dagger (though I have experience with DI from working on Java EE WebApps using Weld).

What I\'m trying to do is to inject a dependency into a class. The

相关标签:
3条回答
  • 2020-12-18 20:04

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

    Dagger doesn't support injection on private fields.

    0 讨论(0)
  • 2020-12-18 20:10

    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.

    0 讨论(0)
  • 2020-12-18 20:31

    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;
    }
    
    0 讨论(0)
提交回复
热议问题