在 Guice 中动态绑定实例

Bind instances dynamically in Guice

注意:尽管名称相似,但Dynamically bind instances using guice的答案无法解决我的问题,因为我需要所有注入直接注入而不是映射。

我有一组 Class -> 实例。它们存储在 Guava 的 ClassToInstanceMap 中。我想将 ClassToInstanceMap 传递给我的自定义 Module 并遍历每个条目以执行实际绑定。我该怎么做?

import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.inject.AbstractModule;
import com.google.inject.Module;

public class InstanceModuleBuilder {
  private final ImmutableClassToInstanceMap.Builder<Object> instancesBuilder = ImmutableClassToInstanceMap.builder();
  public <T> InstanceModuleBuilder bind(Class<T> type, T instance) {
    instancesBuilder.put(type, instance);
    return this;
  }
  public Module build() {
    return new InstanceModule(instancesBuilder.build());
  }
  static class InstanceModule extends AbstractModule {
    private final ImmutableClassToInstanceMap<Object> instances;
    InstanceModule(ImmutableClassToInstanceMap<Object> instances) {
      this.instances = instances;
    }
    @Override protected void configure() {
      for (Class<?> type : instances.keySet()) {
        bind(type).toInstance(instances.getInstance(type)); // Line with error
      }
    }
  }
}

当我编译上面的代码时,出现以下错误:

InstanceModuleBuilder.java:[38,52] incompatible types: inference variable T has incompatible bounds
    equality constraints: capture#1 of ?
    upper bounds: capture#2 of ?,java.lang.Object

我还尝试了以下绑定:

for (Map.Entry<? extends Object,Object> e: instances.entrySet()) {
  bind(e.getKey()).toInstance(e.getValue());
}

for (Map.Entry<? extends Object,Object> e: instances.entrySet()) {
  bind(e.getKey()).toInstance(e.getKey().cast(e.getValue()));
}

但是none编译。

我摆脱了泛型并且它起作用了:

    @Override protected void configure() {
      for (Class type : instances.keySet()) {
        bind(type).toInstance(instances.getInstance(type));
      }
    }