如何在Guice中绑定接口的各种实现
我有一个接口的多个实现的列表。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能做的是:
然后:
但这有点令人费解。还有更好的建议吗?
What I could do is:
and then:
But this is a bit convoluted. Any better suggestion?