What's wrong with my TypeLiteral equivalent of this generic Guice binding method?

45 views
Skip to first unread message

glenviewjeff

unread,
Dec 30, 2011, 3:24:34 PM12/30/11
to google...@googlegroups.com
Also posted on Stack Overflow.

I have a follow-up question about further abstracting my generic method.  Thanks to Stuart for the great help that allowed me to get this far.

The following generic Guice binding method now behaves correctly:

<T> Key<?> bindMultibinder(
   
ArrayList<Class<? extends T>> contents, Class<T> superClass) {
   
Named annotation = randomAnnotation();
   
Multibinder<T> options =
   
Multibinder.newSetBinder(binder(), superClass, annotation);
   
for (Class<? extends T> t : contents) {
      options
.addBinding().to(t);
   
}
   
final Key<?> multibinderKey = Key.get(Types.setOf( superClass ), annotation);
   
return multibinderKey;
}

And uses client code like this:

ArrayList<Class<? extends Option>> options = 
 
new ArrayList<Class<? extends Option>>();
options
.add(CruiseControl.class);
bindMultibinder
(options, Option.class);

However, if I want to allow Option take a generic parameter like Option<Radio>, then I assume I need to pass a TypeLiteral in the bindMultibinder superClass parameter. This is my best attempt so far, but I get a Guice binding error "Too many binding definitions given" when I try using the TypeLiteral method.

<T> Key<?> bindMultibinder(
 
ArrayList<TypeLiteral<? extends T>> contents, TypeLiteral<T> superClass) {
   
Named annotation = randomAnnotation();
   
Multibinder<T> options =
   
Multibinder.newSetBinder(binder(), superClass, annotation);
   
for (TypeLiteral<? extends T> t : contents) {
      options
.addBinding().to(t);
   
}
   
final Key<?> multibinderKey = Key.get(superClass, annotation);
   
return multibinderKey;
}

The binding code equivalent to the prior case looks like this:

ArrayList<TypeLiteral<? extends Option>> options = 
 
new ArrayList<TypeLiteral<? extends Option>>();
options
.add(new TypeLiteral<CruiseControl>(){});
bindMultibinder
(options, new TypeLiteral<Option>(){});

Any ideas what I'm doing wrong?


glenviewjeff

unread,
Dec 30, 2011, 4:56:17 PM12/30/11
to google...@googlegroups.com
My problem was that this line:


   
final Key<?> multibinderKey = Key.get(superClass, annotation);

Should have been:

   final Key<?> multibinderKey = Key.get(Types.setOf(superClass.getRawType()), annotation);

Reply all
Reply to author
Forward
0 new messages