roboguice - 如何手动创建一个新的对象
问题描述:
我有一个客户类,我已经注入它的依赖与@Inject注释。我想在这个类中创建一个返回类的新实例的方法。roboguice - 如何手动创建一个新的对象
class Customer{
//the DataSource class is annotated with @Singleton
@Inject protected DataSource dataSource;
public DataSource getDatasource(){
return dataSource;
}
public Customer newInstance(){
return new Customer();
}
}
在我的活动中,我有一个客户通过@Inject注释注入。在onCreate()方法中,我通过调用customer.newInstance()获取另一个Customer实例,但是当我执行以下操作时,第二个Customer对象的数据源为null。如何通过RoboGuice按需创建新对象以确保它具有其依赖性?
if(customer.newInstance().getDatasource() == null){
//This gets logged
Log.d("DEBUG", "2nd customer's datasource is null");
}
任何帮助将不胜感激。
答
想通了下列要求:
class Customer{
//the DataSource class is annotated with @Singleton
@Inject protected DataSource dataSource;
@Inject protected Injector injector;
public DataSource getDatasource(){
return dataSource;
}
public Customer newInstance(){
return injector.getInstance(getClass());
}
}
答
你可以试试下面的方法来建立一个新的对象为您的客户类,
Customer newObject;
newObject = newInstance();