Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Dagger Dependency Injection fails on private Fields

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.

like image 287
salgmachine Avatar asked May 16 '13 21:05

salgmachine


People also ask

Can a dagger inject a private field?

Dagger doesn't support injection on private fields.

What is dagger dependency injection Android?

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.

What is dagger dependency injection?

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.

What is @inject annotation in Android?

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.


1 Answers

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.

like image 137
Christian Gruber Avatar answered Oct 16 '22 16:10

Christian Gruber