代码之家  ›  专栏  ›  技术社区  ›  Matt

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

  •  3
  • Matt  · 技术社区  · 15 年前

    我有几种像这样的

    // 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>
    

    那么比如说,,

    WildcardType kType = Types.subtypeOf(Object.class);
    WildcardType barType = 
       Types.subtypeOf(Types.newParameterizedType(Bar.class, pipeKey));
    ParameterizedType fooType = 
       Types.newParameterizedType(Foo.class, pipelineableType, pipeKey);
    

    实际上,这似乎是错误的,因为它基本上是:

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

    这与:

    Foo<V extends Bar<K>, K>
    

    如后一种情况,我 知道 K是一致类型。

    干杯

    马特

    2 回复  |  直到 13 年前
        1
  •  4
  •   NamshubWriter    15 年前

    来自JavaDoc的 Binder :

    泛型类型,如 Set<E> 全部的 类型参数必须完全匹配 明确规定。

    您可以为创建绑定 Foo 什么时候 K V 你一定会的。 对于不止一种类型的键,您可以创建一个方法,使绑定更容易。一种方法是在您的模块中创建如下方法:

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

    如果你有这些课程:

    class StringValue implements Bar<String> {
      ...
    }
    
    class StringValueProcessor implements Foo<StringValue, String> {
      ...
    }
    

    您可以创建如下绑定:

    bind(String.class, StringValue.class).to(StringValueProcessor.class);
    

    …这样Guice就可以注入这样的类:

    static class Target {
      private final Foo<StringValue, String> foo;
    
      @Inject
      public Target(Foo<StringValue, String> foo) {
        this.foo = foo;
      }
    }
    
        2
  •  0
  •   Jesse Wilson    15 年前

    Guice的工厂无法建立 TypeVariable 实例。您需要根据需要直接实现这个接口。

    请注意,Guice不允许对未完全限定的类型进行绑定。例如,可以绑定 Map<String, Integer> Map<K, V> .