【问题标题】:Bind Class<?> with Guice使用 Guice 绑定 Class<?>
【发布时间】:2013-12-17 12:47:28
【问题描述】:

我有一个不同类的实例列表,我只想将它们中的每一个绑定到自己的类。 我用binder.bind(obj.getClass()).toInstance(obj) 尝试了foreach 循环,但是这当然不能编译,因为编译器无法解析泛型T。 还有什么办法可以做到这一点?

【问题讨论】:

  • 很可能你做错了。如果您的实例列表是静态已知的,那么您应该为每个类执行多次 bind().toInstance() 调用。如果事先不知道此列表,那么您真的应该重新考虑您的设计。 Guice 不应该那样使用。看看multibindings,也许这就是你需要的。

标签: dependency-injection guice


【解决方案1】:

您需要的只是转换为原始类型。正如下面chooks 的评论(谢谢!),Guice 有效地充当了从键(通常是类对象)到值(该类的提供者)的映射,而泛型只是有助于保持常见情况的理智。如果你确定你的键匹配,你可以像这样覆盖泛型:

@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 的绑定。此外,您的初始化单例列表中的所有类都必须在没有 Guice 注入本身的好处的情况下创建,因此您将自己限制为在没有 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.
}

【讨论】:

  • 这是一个很好的答案。为 OP 添加一点价值——如果您阅读了 guice 如何使用 Key 值在内部存储绑定,那么这可能会让您更清楚地了解如何使用泛型。我知道我在用我的代码进行概念转换时遇到了问题(使用了很多参数化类型/方法/等...),最终了解实际的绑定机制使得解决涉及泛型和使用事物的问题变得更加清晰像 TypeLiterals。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
相关资源
最近更新 更多