views:

86

answers:

1
+1  Q: 

Google Guice 2.0

I have a class that loads some files into a specific object that itself contains several objects that contain different fields. Exmaple:

class RootItem
{
public SubItemType1 sub1;
}

class SubItemType1
{
public SubItemType2 sub2;
public int data1;
public float data2;
}

class SubItemType2
{
public int data3;
public boolean data4;
}

Alright now I have another class that contains a method that will return a RootItem with all of the sub-items set to specific values.

Then I would like to, using Guice, be able to call that loader once and then whenever someone requests an @Inject of the SubItemType1 class then the RootItem.sub1 object is returned and if someone requests a SubItemType2 class then RootItem.sub1.sub2 is returned.

Can this be achived?

Thanks,

ExtremeCoder

+3  A: 

In your module:

private RootItem rootItem; /* Initialize this field e.g. in the module's constructor */

@Provides
RootItem provideRootItem() {
    return rootItem;
}

@Provides
SubItemType1 provideSubItemType1() {
    return rootItem.sub1;
}

@Provides
SubItemType2 provideSubItemType2() {
    return rootItem.sub1.sub2;
}

Then you can inject the RootItem, SubItemType1 and SubItemType2 in your code as usual.

Chris Lercher
(Alternatively, you can use bind(RootItem.class).toInstance(rootItem) etc. - I personally prefer the @Provides methods, because they also work with Google Gin)
Chris Lercher