javagwtdependency-injectionguicegwt-gin

How to get a extended SubClass from Google Gin using GinFactoryModuleBuilder?


The GinFactoryModuleBuilder class comment says the following:

In difference to regular Guice Assisted Inject, in Gin, return types in your factory are not further resolved using your regular injector configuration. This means that in the following example you'll still get a Chicken and not a Rooster:

interface Animal {}
 public class Chicken implements Animal {}
 public class Rooster extends Chicken {}
 interface AnimalFactory {
   Animal getAnimal();
 }
 ...
 protected void configure() {
   bind(Chicken.class).to(Rooster.class);
   install(new GinFactoryModuleBuilder()
       .implement(Animal.class, Chicken.class)
       .build(AnimalFactory.class));
 }

Is there a way to get the Rooster class in gin? What about:

install(new GinFactoryModuleBuilder()
        .implement(Animal.class, Rooster.class)
        .build(AnimalFactory.class));

And in my code:

@Inject
AnimalFactory f;
Animal rooster = f.getAnimal();

How do I create the Rooster?

How to get a extended SubClass from Google Gin using GinFactoryModuleBuilder?


Solution

  • You can just remove everything from the configure method and keep only the following :

    install(new GinFactoryModuleBuilder()
      .implement(Animal.class, Rooster.class)
      .build(AnimalFactory.class));
    

    and then use the factory as you did to get instance of Rooster from the factory.

    Or, you can change your factory method to return Rooster & change configure as follows, and use the factory as you did :-

    interface AnimalFactory {
       Rooster getAnimal();
     }
     ...
     protected void configure() {
       install(new GinFactoryModuleBuilder().build(AnimalFactory.class));
     }