我正在尝试使用泛型注入实例,但出现以下错误:
HasOne<ModelClass> cannot be used as a key; It is not fully specified.
我在其他地方读到过,最安全的方法是在使用注入器获取实例时显式命名要在泛型中使用的类,但我想更简洁一些。我正在尝试Relationship
在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
课堂上