2016-12-28 65 views
1

注意:儘管名稱相似,但Dynamically bind instances using guice的答案無法解決我的問題,因爲我需要直接注入所有注入而不是地圖。我有一組Class - >實例。它們儲存在番石榴的ClassToInstanceMap中。我想將ClassToInstanceMap傳遞給我的自定義Module並遍歷每個條目以執行實際綁定。我怎麼做?在Guice中動態綁定實例

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())); 
} 

但沒有編譯。

回答

2

我擺脫了仿製藥和它的工作:

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