【问题标题】:Guice annotatedWith for interface with GenericsGuice annotatedWith 用于与泛型的接口
【发布时间】:2011-02-11 09:21:08
【问题描述】:

我有一个接口 TestInterface 有许多实现,当我使用 Guice 进行绑定时,我收到一条消息说 TestInterface 未绑定到实现。以下是我用来将接口与其实现绑定的语法。

bind(TestInterface.class).annotatedWith(Names.named("Impl1Test")).to(Impl1.class);

附言我用一个虚拟接口进行了测试,但没有泛型,它工作得很好,我认为泛型需要做一些特殊的事情。

【问题讨论】:

    标签: guice


    【解决方案1】:

    绑定泛型类型时,您需要使用TypeLiteral 而不是原始的class。否则,Guice 将无法区分泛型类型。在您的情况下,它看起来像这样:

    bind(new TypeLiteral<TestInterface<Impl1, Impl2>>(){})
        .annotatedWith(Names.named("Impl1Test"))
        .to(Impl1.class);
    

    如果您没有其他要绑定为TestInterface&lt;Impl1, Impl2&gt; 的东西,您甚至可能不需要annotatedWith。请注意 {} 在创建 TypeLiteral... 时需要 TypeLiteral 的匿名子类才能保留泛型类型信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 2014-12-16
      • 1970-01-01
      • 2023-02-21
      • 2014-08-22
      相关资源
      最近更新 更多