问题
How can I abstract the Option type in the below Guice binding code, substituting a generic parameter for Option
?
ArrayList<Class<? extends Option>> options =
new ArrayList<Class<? extends Option>>();
bindMultibinder(annotation, options);
public Key<Set<Option>> bindMultibinder(
Named annotation, ArrayList<Class<? extends Option>> contents) {
Multibinder<Option> options =
Multibinder.newSetBinder(binder(), Option.class, annotation);
for (Class<? extends Option> option : contents) {
options.addBinding().to(option);
}
final Key<Set<Option>> multibinderKey =
Key.get(new TypeLiteral<Set<Option>>(){}, annotation);
return multibinderKey;
}
回答1:
Thanks to Stuart McCulloch on Google Groups for answering:
^ the new TypeLiteral<...>(){} anonymous class trick only works when the type parameter is known at compile time.
If you need to build generic types at runtime you can use the com.google.inject.util.Types utility class, for example:
final Key<Set<T>> multibinderKey =
Key.get( Types.setOf( superClass ), annotation );
To get this to build correctly, I modified it as follows:
final Key<?> multibinderKey = Key.get(Types.setOf( superClass ), annotation);
So the complete generic method is:
public <T> Key<?> bindMultibinder(
Named annotation, Class<T> superClass, ArrayList<Class<? extends T>> contents) {
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;
}
回答2:
java.util.Set<T> cannot be used as a key; It is not fully specified.
Says to me that Guice Key
doesn't support using Generics - you can only have something fully specified (i.e. with no unbound type parameters).
来源:https://stackoverflow.com/questions/8672431/how-can-i-write-a-generic-guice-binding-function