注射仿制药与roboguice

我正在尝试使用generics注入实例,并且我收到以下错误:

HasOne cannot be used as a key; It is not fully specified. 

我在其他地方读过,最安全的方法是在使用注入器获取实例时明确命名要在generics中使用的类,但我想要更清洁一点。 我正在尝试在Models之间创建Relationship对象。

这是我简化的Model

 public class Model { @Inject Injector injector; public  HasOne hasOne(Class clazz) { HasOne hasOne = injector.getInstance(Key.get(new TypeLiteral<HasOne>() { })); hasOne.init(clazz); return hasOne; } } 

我的HasOne关系

 public class HasOne { Class clazz; public void init(Class 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(){ return hasOne(ExampleModel.class); } } 

测试Model #2

 public class ExampleModel extends Model { } 

这样做时我收到错误

  TestModel testModel = RoboGuice.getInjector(context).getInstance(TestModel.class); HasOne relationship = testModel.exampleModel(); 

我试图隐藏丑陋的关系创建并将其保留在Model类中

如果T是类型参数,则不能使用new TypeLiteral() { } ,它必须是完全指定的类型。 幸运的是,既然你有一个Class的实例,你可以这样做:

 (Key>) Key.get(TypeLiteral.get(Types.newParameterizedType(HasOne.class, clazz))) 

你会得到关于演员阵容的警告但是可以安全地压制它。