How can I write a generic Guice binding function?

别来无恙 提交于 2019-12-12 21:25:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!