具有类型参数的Guice模块

los*_*iuk 9 java generics guice

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

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

interface A<T> {} 
class AImpl<T> implements A<T>{} 
interface B<T> {} 
class BImpl<T> implements B<T> {} 

class MyModule<T> extends AbstractModule { 
    @Override 
    protected void configure() { 
        bind(new TypeLiteral<A<T>>(){}).to(new TypeLiteral<AImpl<T>>(){});
        bind(new TypeLiteral<B<T>>(){}).to(new TypeLiteral<BImpl<T>>(){}); 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

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

此致,ŁukaszOsipiuk

jfp*_*ret 12

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

class MyModule<T> extends AbstractModule {
    public MyModule(TypeLiteral<T> type) {
        _type = type;
    }

    @Override protected void configure() {
        TypeLiteral<A<T>> a = newGenericType(A.class);
        TypeLiteral<AImpl<T>> aimpl = newGenericType(AImpl.class);
        bind(a).to(aimpl);
        TypeLiteral<B<T>> b = newGenericType(B.class);
        TypeLiteral<BImpl<T>> bimpl = newGenericType(BImpl.class);
        bind(b).to(bimpl);
    }

    @SuppressWarnings("unchecked")
    private <V> TypeLiteral<V> newGenericType(Class<?> base) {
        Type newType = Types.newParameterizedType(base, _type.getType());
        return (TypeLiteral<V>) TypeLiteral.get(newType);
    }

    final private TypeLiteral<T> _type;
}
Run Code Online (Sandbox Code Playgroud)

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