gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:03:28 25 4
gpt4 key购买 nike

GinFactoryModuleBuilder 类注释如下:

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

有没有办法在 Gin 中获得 Rooster 类?怎么样:

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 实例一样使用工厂。

或者,您可以更改工厂方法以返回 Rooster 并更改配置,如下所示,然后像您一样使用工厂:-

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

关于java - 如何使用 GinFactoryModuleBuilder 从 Google Gin 获取扩展子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com