2016-12-28 3 views
1

참고 : 유사한 이름에도 불구하고 Dynamically bind instances using guice의 대답은지도에 직접 주입하지 않고 모든 주입을 필요로하므로 내 문제를 해결할 수 없습니다.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 
     } 
    } 
    } 
} 

, 나는 다음과 같은 오류가 발생합니다 :

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

그러나 :

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 

은 또한 다음과 같은 바인딩을 시도 없음 컴파일.

답변

2

내가 제네릭을 제거있어하고 일 :

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