Java 在Guice中动态绑定实例

Java 在Guice中动态绑定实例,java,guice,Java,Guice,注意:尽管名称相似,但的答案不能解决我的问题,因为我需要所有的注射都直接注射,而不是在地图上 我有一组成对的类->实例。它们存储在番石榴的ClassToInstanceMap中。我想将该ClassToInstanceMap传递给我的自定义模块,并遍历每个条目以执行实际绑定。我该怎么做 import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.inject.AbstractModule; impo

注意:尽管名称相似,但的答案不能解决我的问题,因为我需要所有的注射都直接注射,而不是在地图上

我有一组成对的
->实例。它们存储在番石榴的
ClassToInstanceMap
中。我想将该
ClassToInstanceMap
传递给我的自定义
模块
,并遍历每个条目以执行实际绑定。我该怎么做

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
      }
    }
  }
}
我还尝试了以下绑定:

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

for(Map.Entry我去掉了泛型,它成功了:

    @Override protected void configure() {
      for (Class type : instances.keySet()) {
        bind(type).toInstance(instances.getInstance(type));
      }
    }
for (Map.Entry<? extends Object,Object> e: instances.entrySet()) {
  bind(e.getKey()).toInstance(e.getKey().cast(e.getValue()));
}
    @Override protected void configure() {
      for (Class type : instances.keySet()) {
        bind(type).toInstance(instances.getInstance(type));
      }
    }