如何在Guice中绑定接口的各种实现

发布于 2025-01-11 16:34:34 字数 779 浏览 0 评论 0原文

我有一个接口的多个实现的列表。

public class MyInterfaceImplementation1 extends MyInterface {}

public class MyInterfaceImplementation2 extends MyInterface {}

...

List<MyInterface> myInterfaceImplementationList;
myInterfaceImplementationList.add(new MyInterfaceImplementation1);
myInterfaceImplementationList.add(new MyInterfaceImplementation2);

列表被传递到我的 AbstractModule 实现中,我想根据具体类动态绑定它们。 比如:

for (MyInterface c : myInterfaceImplementationList) {
  bind(c.getClass()).toInstance(c); //this is not OK
}

现在,这在 Guice 中可能吗?如何实现?

后来我想访问具体的实现:

injector.getInstance(MyInterfaceImplementation1.class);
injector.getInstance(MyInterfaceImplementation2.class);
...

I have a list of multiple implementations of an interface.

public class MyInterfaceImplementation1 extends MyInterface {}

public class MyInterfaceImplementation2 extends MyInterface {}

...

List<MyInterface> myInterfaceImplementationList;
myInterfaceImplementationList.add(new MyInterfaceImplementation1);
myInterfaceImplementationList.add(new MyInterfaceImplementation2);

List is passed into my implementation of AbstractModule, where I would like to bind them dynamically based on concrete Class.
Something like:

for (MyInterface c : myInterfaceImplementationList) {
  bind(c.getClass()).toInstance(c); //this is not OK
}

Now, is this possible in Guice and how?

Later I would like to access concrete implementation:

injector.getInstance(MyInterfaceImplementation1.class);
injector.getInstance(MyInterfaceImplementation2.class);
...

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

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

发布评论

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

评论(1

谜兔 2025-01-18 16:34:34

我能做的是:

for (MyInterface c : myInterfaceImplementationList) {
  bind(MyInterface.class).annotatedWith(Names.named(c.getClass().getName())).toInstance(c); 
}

然后:

(MyInterfaceImplementation1) injector.getInstance(Key.get(MyInterface.class, Names.named(MyInterfaceImplementation1.class.getName())));

但这有点令人费解。还有更好的建议吗?

What I could do is:

for (MyInterface c : myInterfaceImplementationList) {
  bind(MyInterface.class).annotatedWith(Names.named(c.getClass().getName())).toInstance(c); 
}

and then:

(MyInterfaceImplementation1) injector.getInstance(Key.get(MyInterface.class, Names.named(MyInterfaceImplementation1.class.getName())));

But this is a bit convoluted. Any better suggestion?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文