无法使用Guice绑定TypeLiteral

时间:2018-06-04 14:03:55

标签: java guice

我开始学习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);
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

You should use the following instead:

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

Just because you have a TypeLiteral as interface doesn't mean you have to use type literals as implementation.

Also, change your 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);
    }
}