如何使用 Guice 注入通用参数?

发布于 2024-12-28 01:39:54 字数 192 浏览 3 评论 0原文

我发现了其他相关问题,但没有一个如此简单:

How can I bind the following generic argument using Guice?

class A<T> {
   T a;
   @Inject A(T a) {
      this.a=a;
   }
}

I found other related questions, but none so straightforward:

How can I bind the following generic parameter using Guice?

class A<T> {
   T a;
   @Inject A(T a) {
      this.a=a;
   }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘你却要生生世世 2025-01-04 01:39:54
public class TestGenericBinding {
   static class A<T> {
      T a;
      @Inject A(T a) {
         this.a=a;
      }
   }

    @Test public void bindingWorked() {
       Injector injector = Guice.createInjector(new AbstractModule() {

         @Override
         protected void configure() {
            bind(Integer.class).toInstance(123);
            bind(new TypeLiteral<A<Integer>>() {});
         }
      });
       A<Integer> a = injector.getInstance(
          Key.get(new TypeLiteral<A<Integer>>(){}));
       assertEquals(new Integer(123),a.a);
    }
}
public class TestGenericBinding {
   static class A<T> {
      T a;
      @Inject A(T a) {
         this.a=a;
      }
   }

    @Test public void bindingWorked() {
       Injector injector = Guice.createInjector(new AbstractModule() {

         @Override
         protected void configure() {
            bind(Integer.class).toInstance(123);
            bind(new TypeLiteral<A<Integer>>() {});
         }
      });
       A<Integer> a = injector.getInstance(
          Key.get(new TypeLiteral<A<Integer>>(){}));
       assertEquals(new Integer(123),a.a);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文