2013-05-10 21 views
0

我有一個客戶類,我已經注入它的依賴與@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"); 
} 

任何幫助將不勝感激。

回答

1

想通了下列要求:

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()); 
    } 
} 
0

你可以試試下面的方法來建立一個新的對象爲您的客戶類,

Customer newObject; 

newObject = newInstance(); 
相關問題