我如何编写一个通用的Guice绑定函数? [英] How can I write a generic Guice binding function?

查看:139
本文介绍了我如何编写一个通用的Guice绑定函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在下面的Guice绑定代码中抽象出Option类型,用 Option

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


推荐答案

感谢 Stuart McCulloch 回答:

Thanks to Stuart McCulloch on Google Groups for answering:


新的TypeLiteral< ...>(){}匿名类技巧仅在
类型参数在编译时已知的情况下才有效

^ the new TypeLiteral<...>(){} anonymous class trick only works when the type parameter is known at compile time.

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

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

这篇关于我如何编写一个通用的Guice绑定函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆