无法使用 Guice 绑定类型文字



我开始学习Guice,但我已经遇到了一个问题。当我尝试绑定类型文字时,我收到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);
}

二十一点卡随机发生器.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); 

仅仅因为您有一个TypeLiteralas 接口并不意味着您必须使用类型文本作为实现。

另外,更改您的extends

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

相关内容

  • 没有找到相关文章

最新更新