我开始学习Guice,但是我已经遇到了问题。当我尝试绑定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);
    }
}


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

07-27 18:18