gpt4 book ai didi

java - Guice - 以编程方式创建的绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 12:10:36 28 4
gpt4 key购买 nike

我正在使用 Guice 进行 DI。我想创建泛型类的动态绑定(bind)来替代我现在创建的手动绑定(bind)。

到目前为止,手动方式运行良好:

        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 ?>)

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

最佳答案

感谢@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);
}

关于java - Guice - 以编程方式创建的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580402/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com