19

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.

4

3 回答 3

39

Dagger 不能支持私有字段,但仍然支持代码生成的适配器(以避免反射)。像 Guice 这样的系统支持私有字段的方式是它们在访问它们之前反射性地更改对字段的访问。由于 dagger 在与要注入的类相同的包中生成 InjectAdapter,因此它可以访问包友好、受保护或公共字段。它不能访问私有字段。

Dagger 的优点之一是它避免了反射,因此使用反射来绕过场可见性并不是一个理想的功能。

于 2013-05-16T22:14:32.250 回答
21

使私有字段“包可见”可能并不总是您想要的。Dagger 文档建议如下:

注入 final 字段和私有成员。为了获得最佳性能,Dagger 会生成代码。通过使用构造函数注入来解决这个问题。

这是一个例子:

private ItemFactoryImpl itemFactory;
private BuildingFactory buildingFactory;

@Inject
public World(ItemFactoryImpl itemFactory, BuildingFactory buildingFactory) {
    this.itemFactory = itemFactory;
    this.buildingFactory = buildingFactory;
}
于 2014-04-27T11:46:43.893 回答
2

只需删除private即可将您的字段的可见性设置为package friendly

Dagger 不支持在私有字段上注入。

于 2013-05-16T22:00:57.570 回答