无法使用 Guice 绑定 TypeLiteral

Can't bind TypeLiteral using Guice

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

这是我要使用 bind() 的 class。

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

Randomizer.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 作为接口并不意味着你必须使用类型文字作为实现。

此外,更改您的 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);
    }
}