What do I do with Guice when I need to call a parent constructor that is also injectable? e.g. I have an abstract parent class that has a constructor that is injected with a
A better alternative is to use something similar to the strategy pattern to encapsulate all the fields the superclass wants to inject, and then the subclass can inject that. For example:
public abstract class Animal {
/**
* All injectable fields of the Animal class, collected together
* for convenience.
*/
protected static final class AnimalFields {
@Inject private Foo foo;
@Inject private Bar bar;
}
private final AnimalFields fields;
/** Protected constructor, invoked by subclasses. */
protected Animal(AnimalFields fields) {
this.fields = fields;
}
public Foo getFoo() {
// Within Animal, we just use fields of the AnimalFields class directly
// rather than having those fields as local fields of Animal.
return fields.foo;
}
public Bar getBar() {
return fields.bar;
}
}
public final class Cat extends Animal {
private final Whiskers whiskers;
// Cat's constructor needs to inject AnimalFields to pass to its superclass,
// but it can also inject whatever additional things it needs.
@Inject
Cat(AnimalFields fields, Whiskers whiskers) {
super(fields);
this.whiskers = whiskers;
}
...
}