Java 具有类型参数的Guice模块

Java 具有类型参数的Guice模块,java,generics,guice,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 AbstractMo

我花了一些时间想知道是否有可能编写一个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>>(){}); 
    } 
} 
接口A{}
类AImpl实现一个{}
接口B{}
类BImpl实现B{}
类MyModule扩展了抽象模块{
@凌驾
受保护的void configure(){
绑定(new-TypeLiteral(){}).to(new-TypeLiteral(){});
绑定(new-TypeLiteral(){}).to(new-TypeLiteral(){});
} 
} 
我尝试了不同的传递方法,试图将T作为的实例传递给MyModule 类/TypeLiteral,但它们都不起作用。 谢谢你的帮助


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

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;
}
MyModule类扩展了AbstractModule{ 公共MyModule(TypeLiteral类型){ _类型=类型; } @覆盖受保护的void configure(){ TypeLiteral a=newGenericType(a.class); TypeLiteral aimpl=newGenericType(aimpl.class); 绑定(a)到(aimpl); TypeLiteral b=newGenericType(b.class); TypeLiteral bimpl=newGenericType(bimpl.class); 绑定(b)到(bimpl); } @抑制警告(“未选中”) 私有TypeLiteral newGenericType(类基){ Type newType=Types.newParameteredType(base,_Type.getType()); return(TypeLiteral)TypeLiteral.get(newType); } 最终私有TypeLiteral_类型; }
请注意,私有方法newGenericType()不会对类型执行任何控制,在
configure()
中,您有责任确保可以使用该方法正确生成泛型类型。

不客气,我很高兴能提供帮助。我知道我已经在我的guts事件库中使用了这种高级的东西,所以从我过去做的例子中改编你的例子并不难。如果我不知道
AImpl
BImpl
类型是什么,我该怎么办?在我的例子中,我正在创建一个库,它公开一个泛型类和相关的guice模块。