如何使用 GinFactoryModuleBuilder 从 Google Gin 获取扩展子类?

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

GinFactoryModuleBuilder class 评论如下:

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));
 }

有没有办法在杜松子酒中加入公鸡 class?怎么样:

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

在我的代码中:

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

如何创建公鸡?

如何使用 GinFactoryModuleBuilder 从 Google Gin 中获取扩展子类?

您可以从配置方法中删除所有内容,只保留以下内容:

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

然后像从工厂获取 Rooster 实例一样使用工厂。

或者,您可以将工厂方法更改为 return Rooster 并按如下方式更改配置,然后像您一样使用工厂 :-

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