Cheryl Simon
Cheryl Simon

Reputation: 46844

Inject key into MapBinder

I am trying to inject a Map into a class using Guice where the map has the form Map<MyInterface, Integer>.

I want to use the MapBinder extention to accomplish this, but it seems that MapBinder requires an instantiated object for the key. I would like to have Guice inject instantiations of the key, since they are complex objects that require injections of their own. I.e, something like:

MapBinder<MyInterface, Integer> mapBinder = 
    MapBinder.newMapBinder(binder(), MyInterface.class, Integer.class);
mapBinder.addBinding(MyInterfaceImpl1.class).to(5);
mapBinder.addBinding(MyInterfaceImpl2.class).to(6);

This is illegal though, since addBinding expects a instance of the class.

I know I could switch the order of the objects in the map, but the integer values are not unique so then I'd end up with a Map of Integer -> List, which is rather ugly. Anyone have any ideas?

Upvotes: 0

Views: 615

Answers (1)

gk5885
gk5885

Reputation: 3762

MapBinder is not going to work for you. The mapping is from static keys to provided values, not the other way around.

Perhaps a more concrete description of what you're trying to do would help uncover a solution.

Also, take a look at Multiset for mapping a type to an integer. I'm not sure if you're modeling a count or not, but it seems like it might fit for what you're trying to do.

Upvotes: 1

Related Questions