Java Guice-以编程方式创建的绑定
我正在使用Guice进行DI。我想创建一个泛型类的动态绑定,以替代我现在创建的手动绑定 到目前为止,手动方式运行良好:Java Guice-以编程方式创建的绑定,java,generics,types,guice,Java,Generics,Types,Guice,我正在使用Guice进行DI。我想创建一个泛型类的动态绑定,以替代我现在创建的手动绑定 到目前为止,手动方式运行良好: bind(new TypeLiteral<DAOService<SourceSystem, UUID>>() {}) .to(new TypeLiteral<DAOServiceImpl<SourceSystem, UUID>>() {}); 但我想说的是: final Strin
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 ?>)
是否有可能在GUI中使用动态创建的TypeLiterals以编程方式创建绑定?多亏了@AndyTurner。删除from-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);
}
为什么要动态执行此操作?您知道它是安全的,因为您构造类型文本的方式。。。因此,一种很有技巧的方法是从类型文本中删除,然后使用原始类型进行操作。@AndyTurner:谢谢-这就解决了问题。