我有一个不同类的实例列表,我只想将它们中的每一个绑定(bind)到它自己的类。
我用 binder.bind(obj.getClass()).toInstance(obj)
尝试了 foreach 循环,但当然这不会编译,因为编译器无法解析通用 T。
还有什么方法可以实现这一点?
最佳答案
这里您只需要转换为原始类型。如 chooks下面的评论(谢谢!),Guice 有效地充当从键(通常是类对象)到值(该类的提供者)的映射,而泛型只是帮助保持常见情况的理智。如果您确定您的 key 匹配,您可以像这样覆盖泛型:
@Override
protected void configure() {
for (Object object : getYourListOfInitializedObjects()) {
bindObjectAsSingleton(object);
}
}
/** Suppress warnings to convince the Java compiler to allow the cast. */
@SuppressWarnings({"unchecked", "rawtypes"})
private void bindObjectAsSingleton(Object object) {
bind((Class) object.getClass()).toInstance(object);
}
作为Vladimir上面提到,这往往不鼓励好的 Guice 设计,因为即使你有你的 DependencyImpl
实现 Dependency
,上面只会创建到 DependencyImpl的绑定(bind)
。此外,初始化单例列表中的所有类都必须在没有 Guice 注入(inject)的情况下创建,因此您将自己限制在没有 Guice 帮助的情况下从外部初始化的类。如果您要从遗留的“一堆单例”迁移到 Guice,您可能会使用上述模式,但如果您尽快像这样构造您的 configure
方法,您可能会走得更远:
@Override
public void configure() {
// Let Guice create DependencyOne once, with injection,
// immediately on injector creation.
bind(DependencyOne.class).asEagerSingleton();
// Let Guice create DependencyTwo once, with injection,
// but this way you can hopefully rely on interface DependencyTwo
// rather than concrete implementation DependencyTwoImpl.
bind(DependencyTwo.class).to(DependencyTwoImpl.class).asEagerSingleton();
// Bind DependencyThree to an instance. Instance bindings are
// implicitly singletons, because you haven't told Guice how to
// create another one.
bind(DependencyThree.class).toInstance(getDependencyThreeInstance());
// ...and so forth for everything in your list.
}
关于dependency-injection - 使用 Guice 绑定(bind)类 <?>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634568/