So, I\'m currently redesigning an Android app of mine to use Dagger. My app is large and complicated, and I recently came across the following scenario:
Object A requir
Jake's post is great, but there is more simple way. Google created AutoFactory library for creating factory automatically at compile time.
First, create class A
with @AutoFactory
annotation and @Provided
annotation for injecting arguments:
@AutoFactory
public class A {
private DebugLogger logger;
public A(@Provided DebugLogger logger, int amount, int frequency) {
this.logger = logger;
}
}
Then library creates AFactory
class at compile time. So you need just inject the factory to a constructor of B
class.
public class B {
private final AFactory aFactory;
@Inject
public B(AFactory aFactory) {
this.aFactory = aFactory;
}
public A createA(int amount, int frequency) {
return aFactory.create(amount, frequency);
}
}