0

我希望能夠注入一個對象,並將參數傳遞給它的初始化方法。 這可能嗎?Android和Guice - 如何傳遞參數?

public class MyObject 
{ 
    @Inject 
    public MyObject(int anInteger) 
    { 
    //do something 
    } 
} 


public class MyActivity extends RoboActivity 
{ 
    @Inject (anInteger = 5) MyObject myObject; 
    // I want to be able to pass an object to be used when calling the 
    // initializer method 
} 

回答

0
public class MyModule extends AbstractModule 
{ 
    @Override 
    protected void configure() 
    { 
    bind(Integer.class). 
     annotatedWith(Names.named("my.object.an.integer")). 
     toInstance(500); 
    } 

    @Provides 
    @Named("an.integer.5") 
    public MyObject myObject5() 
    { 
    return createMyObject(5); 
    } 

    @Provides 
    @Named("an.integer.100") 
    public MyObject providesMyObject100() 
    { 
    return createMyObject(100); 
    } 

    private MyObject createMyObject(int anInteger) 
    { 
    MyObject result = new MyObject(anInteger); 
    // if there are any other fields/setters annotated with @Inject 
    requestInjection(result); 
    return result; 
    } 
} 


public class MyObject 
{ 
    public MyObject(int anInteger) 
    { 
    System.out.println("anInteger = " + anInteger); 
    } 
} 

public class User 
{ 
    @Inject 
    @Named("an.integer.5") 
    private field MyObject five; 

    @Inject 
    @Named("an.integer.100") 
    private field MyObject hundred; 
} 
+0

謝謝。但那不是我的意思。我想在注入對象時在我的活動中指定變量。例如:@Inject(anInteger = 5)MyObject myObject;當這個get的調用傳遞給教師方法5時,這樣我可以在不同的活動中傳遞不同的對象 – aryaxt 2011-03-30 21:09:36

+1

然後你應該使用@Provides方法 – 2011-03-31 07:16:26