如何编写通用的Guice绑定函数?

时间:2011-12-29 19:23:34

标签: java generics guice

如何在下面的Guice绑定代码中抽象Option类型,用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;
}

2 个答案:

答案 0 :(得分:2)

感谢Google网上论坛上的Stuart McCulloch回复:

  

^新的TypeLiteral&lt; ...&gt;(){}匿名类技巧仅在以下情况下有效   type参数在编译时是已知的。

     

如果需要在运行时构建泛型类型,可以使用   com.google.inject.util.Types实用程序类,例如:

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

为了正确构建,我按如下方式对其进行了修改:

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

所以完整的通用方法是:

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;
}

答案 1 :(得分:1)

  

java.util.Set<T> cannot be used as a key; It is not fully specified.

我认为Guice Key不支持使用泛型 - 你只能有一些完全指定的东西(即没有未绑定的类型参数)。

相关问题