2011-11-26 54 views
2

我有以下类别:谷歌吉斯 - multibinding +仿制药+ assistedinject

public interface Factory<T extends MyParentClass> { 
    public T create(String parameter); 
} 

public class FactoryImpl1 implements Factory<MyChildClass1> { 
    public MyChildClass1 create(String parameter){ 
    ... 
    } 
} 

public class FactoryImpl2 implements Factory<MyChildClass2> { 
    public MyChildClass2 create(String parameter){ 
    ... 
    } 
} 

public class MyModule extends AbstractModule { 
    @Override 
    protected void configure() { 
     MapBinder<String, Factory<MyParentClass>> factoryMap = MapBinder.newMapBinder(binder(), new TypeLiteral<String>() {}, new TypeLiteral<Factory<MyParentClass>>(){}); 
     factoryMap.addBinding("myKey1").to(FactoryImpl1.class); 
     factoryMap.addBinding("myKey2").to(FactoryImpl2.class); 
    } 
} 

我的模块中的语法是不正确的,我don'know如何配置这一点。

其实我想对每一个可能的一家工厂在我厂的接口提前

感谢您的帮助。

回答

1

Factory<MyParentClass>不是超类型Factory<MyChildClass1>,您需要指定通配符泛型(在这种情况下绑定或非绑定并不重要,因为您已经在Factory定义中绑定了它)。

尝试用

MapBinder<String, Factory<?>> factoryMap = MapBinder.newMapBinder(binder(), new TypeLiteral<String>(){}, new TypeLiteral<Factory<?>>(){}); 

检查here仿制药之间的关系父。

+0

感谢Geno为您的解决方案,但我试图避免“演员”。可能吗 ?因为如果我使用你的解决方案,我需要做一个明确的强制转换:MyChildClass1 myChildClass1 =(MyChildClass1)factoryMap.get(“myKey1”).create(“myParameter”);当我将一个字符串键绑定到我的模块中的一个特殊实现时,我不想再次确定这个实现。 – Manu

+0

@Manu如果你的代码已知具体的子类型,那么你不需要地图联编程序。您可以直接注入特定的工厂。如果您的代码只能看到“MyParentClass”并且不关心具体的实现将会收到,MapBinder是有用的。 –

+0

你说得对。谢谢你的帮助。 – Manu