gpt4 book ai didi

java - 无法使用 Guice 绑定(bind) TypeLiteral

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:39 25 4
gpt4 key购买 nike

我正在开始学习Guice,但是我已经遇到了一个问题。当我尝试绑定(bind) TypeLiteral 时,我收到 Cannot resolve method 'to(anonymous com.google.inject.TypeLiteral<> 。我试图寻找问题的原因,但没有效果。也许有人知道如何解决这个问题?

这是我想使用的类 bind() .

public class MainModule extends AbstractModule {
protected void configure(){
bind(DeckFactory.class).to(BlackjackDeckCreator.class);
bind(CardFactory.class).to(BlackjackCardCreator.class);
bind(PointsCalculator.class)
.to(BlackjackPointsCalculator.class);
bind(Logic.class)
.toProvider(CompositeGameLogicStrategyProvider.class);
// Problem
bind(new TypeLiteral<Randomizer<BlackjackCard>>() { })
.to(new TypeLiteral<BlackjackCardRandomizer>() {});
//
bind(DecisionTaker.class)
.toProvider(CompositeDecisionTakerProvider.class);
bind(StatisticPrinter.class)
.to(ConsoleStatisticPrinter.class);
bind(HitGameLogicStrategy.class)
.toProvider(HitGameLogicProvider.class);
bind(StandGameLogicStrategy.class)
.toProvider(StandGameLogicProvider.class);
install(new FactoryModuleBuilder().build(GameFactory.class));
install(new FactoryModuleBuilder()
.build(PlayerFactory.class));
bind(StatisticsTemplate.class)
.toProvider(StatisticsTemplateProvider.class);
}
}

随机化器.java

public interface Randomizer<T extends Card> {
T randomizeCard(List<T> deck);
}

BlackjackCardRandomizer.java

public class BlackjackCardRandomizer implements Randomizer {
private static final Random RANDOM = new Random();

@Override
public Card randomizeCard(List deck) {
Integer randIndex = RANDOM.nextInt(deck.size());
return (Card) deck.get(randIndex);
}
}

提前致谢!

最佳答案

您应该使用以下内容:

bind(new TypeLiteral<Randomizer<BlackjackCard>>() { })
.to(BlackjackCardRandomizer.class);

仅仅因为您有一个 TypeLiteral 作为接口(interface),并不意味着您必须使用类型文字作为实现。

此外,更改您的扩展:

public class BlackjackCardRandomizer implements Randomizer<BlackjackCard> {
private static final Random RANDOM = new Random();

@Override
public BlackjackCard randomizeCard(List<BlackjackCard> deck) {
Integer randIndex = RANDOM.nextInt(deck.size());
return (Card) deck.get(randIndex);
}
}

关于java - 无法使用 Guice 绑定(bind) TypeLiteral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50682460/

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