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?
final Key<?> multibinderKey = Key.get(superClass, annotation);