Using Dagger you would need to turn your fooList
into a dependency of your Foo
class. You'd do that by annotating it with @Inject
. That will tell Dagger that when Foo
gets created by Dagger, that also List<String> fooList
needs to be injected. Keep in mind that the fooList
isn't private in my example. Because Dagger doesn't use reflexion and uses code generation instead you have to declare injectable fields as public or private scope.
public class Foo {
@Inject
@Named("FooDependency")
List<String> footList;
// getter and setter
}
Here since List is a common type we annotate it with @Named("FooDependency")
where "FooDependency" can be any string you desire. We do that because it's at all possible that you'd want to inject another List<String>
else where in the app and we'd want to be able to differentiate between the 2. The other List<String>
could be annotated with @Named("ADifferentDependency")
for example.
Then you'll need to annotate a method with @Provide
in one of your modules which would take care of providing that dependency.
@Module(injects = Foo.class)
public class SomeModule {
@Provide
@Named("FooDependency")
public List<String> provideFooDependencyListOfString() {
return Arrays.asList("1", "2", "3");
}
}
Then you can use it
ObjectGraph objectGraph = ObjectGraph.create(new SomeModule());
Foo foo = objectGraph.get(Foo.class);