Android Dagger Dependency Injection fails on private Fields

一个人想着一个人 提交于 2019-12-06 17:18:04

问题


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 field is private.

Dagger then throws an exception stating it can't inject into a private field.

What's the reason for that?

After all it is possible to write to private fields using reflections, even on android..

If I set the visibility of the field to something other than private the injection seems to work.


回答1:


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;
}



回答2:


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.




回答3:


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

Dagger doesn't support injection on private fields.



来源:https://stackoverflow.com/questions/16598123/android-dagger-dependency-injection-fails-on-private-fields

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