用roboguice注入泛型 [英] injecting generics with roboguice
问题描述
我正在尝试使用泛型注入实例,并且出现以下错误:
I'm trying to inject instances with generics and i'm getting the following error:
HasOne<ModelClass> cannot be used as a key; It is not fully specified.
我在其他地方读过,最安全的方法是在使用注入器获取实例时明确命名要在泛型中使用的类,但我想更简洁一些.我正在尝试在Models
之间创建Relationship
对象.
I've read elsewhere that safest way to do this is to explicitly name the class to be used in the generic when using the injector to get an instance but i'd like to be a little cleaner. I'm trying to create Relationship
objects between Models
.
这是我简化的Model
课
public class Model {
@Inject
Injector injector;
public <ModelClass extends Model> HasOne<ModelClass> hasOne(Class<ModelClass> clazz) {
HasOne<ModelClass> hasOne = injector.getInstance(Key.get(new TypeLiteral<HasOne<ModelClass>>() {
}));
hasOne.init(clazz);
return hasOne;
}
}
我的HasOne
关系
public class HasOne<T extends Model> {
Class clazz;
public void init(Class<T> clazz){
this.clazz = clazz;
}
@Inject
Injector injector;
public T get(){
return (T) injector.getInstance(clazz);
}
}
测试Model
#1
public class TestModel extends Model {
public HasOne<ExampleModel> exampleModel(){
return hasOne(ExampleModel.class);
}
}
测试Model
#2
public class ExampleModel extends Model {
}
执行此操作时出现错误
TestModel testModel = RoboGuice.getInjector(context).getInstance(TestModel.class);
HasOne<ExampleModel> relationship = testModel.exampleModel();
我试图隐藏丑陋的关系,并将其保留在Model
类中
I'm trying to hide away the ugly relationship creation and keep it in the Model
class
推荐答案
如果T
是类型参数,则不能使用new TypeLiteral<T>() { }
,它必须是完全指定的类型.幸运的是,由于您有Class<ModelClass>
的实例,因此可以执行以下操作:
You cannot use new TypeLiteral<T>() { }
if T
is a type parameter, it has to be a fully-specified type. Luckily, since you have an instance of Class<ModelClass>
, you can do this:
(Key<HasOne<ModelClass>>) Key.get(TypeLiteral.get(Types.newParameterizedType(HasOne.class, clazz)))
您会在演员表上收到警告,但可以将其隐藏起来.
You'll get a warning on the cast but it is safe to suppress it.
这篇关于用roboguice注入泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!