Guice - 以编程方式创建的绑定

时间:2017-10-05 07:43:12

标签: java generics types guice

我正在使用Guice进行DI。我想创建一个泛型类的动态绑定,作为我现在创建的手动绑定的替代。

到目前为止,手动方式工作正常:

        bind(new TypeLiteral<DAOService<SourceSystem, UUID>>() {})
            .to(new TypeLiteral<DAOServiceImpl<SourceSystem, UUID>>() {});

但我想要这样的事情:

    final String poPackage = PersistableObject.class.getPackage().getName();
    final Reflections r = new Reflections(poPackage);
    final Class<DAOService> ifClass = DAOService.class;
    final Class<DAOServiceImpl> implClass = DAOServiceImpl.class;

    for (Class<? extends PersistableObject> dbClass : r.getSubTypesOf(PersistableObject.class)) {
        final ParameterizedType ifPt = Types.newParameterizedType(ifClass, dbClass, UUID.class);
        final ParameterizedType implPt = Types.newParameterizedType(implClass, dbClass, UUID.class);

        final TypeLiteral<?> fromLiteral = TypeLiteral.get(ifPt);
        final TypeLiteral<?> toLiteral = TypeLiteral.get(implPt);

        bind(fromLiteral).to(toLiteral); // not compiling!
    }

这不能编译,因为:

[50,30] no suitable method found for to(com.google.inject.TypeLiteral<capture#1 of ?>)

是否有可能使用动态创建的TypeLiterals以编程方式在Guice中创建绑定?

1 个答案:

答案 0 :(得分:1)

感谢@AndyTurner。从<?>删除TypeLiteral解决了m的问题。这是编译和工作:

    final Class<UUID> idClass = UUID.class;
    final Class<DAOService> ifClass = DAOService.class;
    final Class<DAOServiceImpl> implClass = DAOServiceImpl.class;

    for (Class<? extends PersistableObject> dbClass : r.getSubTypesOf(PersistableObject.class)) {
        final ParameterizedType ifPt = Types.newParameterizedType(ifClass, dbClass, idClass);
        final ParameterizedType implPt = Types.newParameterizedType(implClass, dbClass, idClass);
        final TypeLiteral fromLiteral = TypeLiteral.get(ifPt);
        final TypeLiteral toLiteral = TypeLiteral.get(implPt);

        bind(fromLiteral).to(toLiteral);
    }