Generics 通过类型和typeliteral使用Guice在运行时重构泛型类型

Generics 通过类型和typeliteral使用Guice在运行时重构泛型类型,generics,reflection,runtime,guice,Generics,Reflection,Runtime,Guice,我有几种像这样的 // a value that is aware of its key type (K) Bar<K> // something that deals with such values and keys Foo<V extends Bar<K>, K> 实际上,这似乎是错误的,因为它基本上是: Foo<V extends Bar<? extends Object>, ? extends Object> FooGu

我有几种像这样的

// a value that is aware of its key type (K)
Bar<K>
// something that deals with such values and keys
Foo<V extends Bar<K>, K>
实际上,这似乎是错误的,因为它基本上是:

Foo<V extends Bar<? extends Object>, ? extends Object> 

FooGuice的工厂无法生成
TypeVariable
实例。您需要根据需要直接实现这个接口

请注意,Guice不允许对未完全限定的类型进行绑定。例如,您可以绑定
映射
,但不能从JavaDoc绑定
映射

Guice当前无法绑定或注入 泛型类型,例如
Set
all 类型参数必须完全匹配 指定的

当绑定
K
V
时,可以为
Foo
创建绑定。 如果需要为一种以上的键类型为
Foo
进行绑定,可以创建一种方法,使这些绑定更容易。一种方法是在您的模块中创建如下方法:

<K, V extends Bar<K>> AnnotatedBindingBuilder<Foo<V, K>> bind(Class<K> keyType,
    Class<V> barType) {
  ParameterizedType bType = Types.newParameterizedType(Bar.class, keyType);
  ParameterizedType fType = Types.newParameterizedType(Foo.class, barType,
      keyType);

  @SuppressWarnings("unchecked")
  TypeLiteral<Foo<V, K>> typeLiteral =
      (TypeLiteral<Foo<V, K>>) TypeLiteral.get(fType);

  return bind(typeLiteral);
}
…这样Guice就可以注入这样的类:

bind(String.class, StringValue.class).to(StringValueProcessor.class);
static class Target {
  private final Foo<StringValue, String> foo;

  @Inject
  public Target(Foo<StringValue, String> foo) {
    this.foo = foo;
  }
}
静态类目标{
私人决赛福福;
@注入
公众目标(富富){
this.foo=foo;
}
}

有趣的是,我没有想过用那种方式绑定。我真正想要的是搜索一组绑定的能力,这些绑定与可能包含一些类型参数的规范相匹配,例如,所有绑定都是Foo,尽管我认为在这种情况下,只需查找Foo就足够了。你看到了吗?是的,这也是我的问题,我已经以一种迄今为止行之有效的方式实现了这一点。。。但我一直想知道如何将其扩展到更一般的情况。经过思考,我甚至不确定它是否需要,因为它实际上只是一个通配符。我需要再考虑一下。。。
class StringValue implements Bar<String> {
  ...
}

class StringValueProcessor implements Foo<StringValue, String> {
  ...
}
bind(String.class, StringValue.class).to(StringValueProcessor.class);
static class Target {
  private final Foo<StringValue, String> foo;

  @Inject
  public Target(Foo<StringValue, String> foo) {
    this.foo = foo;
  }
}