具有类型参数的Guice模块

我花了一些时间想知道是否可以编写一个guice模块,它本身是用类型T参数化的,并使用它的类型参数来指定绑定。

就像在这个(不工作)的例子中一样:

interface A {} class AImpl implements A{} interface B {} class BImpl implements B {} class MyModule extends AbstractModule { @Override protected void configure() { bind(new TypeLiteral<A>(){}).to(new TypeLiteral<AImpl>(){}); bind(new TypeLiteral<B>(){}).to(new TypeLiteral<BImpl>(){}); } } 

我尝试了不同的方法,尝试将T传递给MyModule作为Class / TypeLiteral的实例但没有一个工作。 帮助赞赏。

此致,ŁukaszOsipiuk

为此,您必须使用com.google.inject.util.Types从头开始构建每个TypeLiteral。 你可以这样做:

 class MyModule extends AbstractModule { public MyModule(TypeLiteral type) { _type = type; } @Override protected void configure() { TypeLiteral> a = newGenericType(A.class); TypeLiteral> aimpl = newGenericType(AImpl.class); bind(a).to(aimpl); TypeLiteral> b = newGenericType(B.class); TypeLiteral> bimpl = newGenericType(BImpl.class); bind(b).to(bimpl); } @SuppressWarnings("unchecked") private  TypeLiteral newGenericType(Class base) { Type newType = Types.newParameterizedType(base, _type.getType()); return (TypeLiteral) TypeLiteral.get(newType); } final private TypeLiteral _type; } 

请注意,私有方法newGenericType()将不对类型执行任何控制,在configure() ,您有责任确保可以使用该方法正确构建generics类型。