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.
Dagger doesn't support injection on private fields.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
Dagger is a fully static, compile-time dependency injection framework for Java, Kotlin, and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.
For Android, these annotations are part of the Roboguice framework. They are used to provide dependency injection in an Android environment. This allows you to directly inject an instance of the desired resource, whether it's a basic POJO, a view, or another resource.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With