在Guice中动态绑定实例

时间:2016-12-28 15:11:39

标签: java guice

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

我有一对Class - >实例。它们存储在番石榴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()));
}

但没有编译。

1 个答案:

答案 0 :(得分:2)

我摆脱了仿制药,它起作用了:

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