christophmccann christophmccann - 11 months ago 42
Java Question

Guice with parents

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 an object shared by all derived children and each child also has an injectable constructor.

Calling super() wont work because Java wants me to pass in the object as a paremeter rather than have Guice inject.


EDIT: I am wondering if maybe I need to use method injection instead?

Answer Source

You'd need to do the exact same thing you do if you weren't using Guice... declare any parameters the parent constructor requires as parameters to each child's constructor as well, and pass those to super.

So if your abstract parent class's constructor takes a Foo, a child class's constructor needs to look like:

@Inject public ChildClass(Foo foo, Bar bar) {
  super(foo); = bar;