generics - 在运行时使用 Guice 通过 Types 和 TypeLiterals 重构泛型类型

标签 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 以便您可以在 Guice 中使用它?我坚持的一点是如何将 K 从 Bar 交叉引用到 Foo 的第二个参数化类型。

例如,
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 是一致的类型。

有任何想法吗?

干杯

马特

最佳答案

来自 Binder 的 JavaDoc :

Guice cannot currently bind or inject a generic type, such as Set<E> all type parameters must be fully specified.



您可以为 Foo 创建绑定(bind)当KV绑定(bind)。
如果您需要绑定(bind)Foo对于不止一种类型的键,您可以创建一种方法来更轻松地进行这些绑定(bind)。一种方法是在你的模块中创建一个这样的方法:
<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):
class StringValue implements Bar<String> {
  ...
}

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

您可以像这样创建绑定(bind):
bind(String.class, StringValue.class).to(StringValueProcessor.class);

...这样 Guice 就可以注入(inject)这样的类:
static class Target {
  private final Foo<StringValue, String> foo;

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

关于generics - 在运行时使用 Guice 通过 Types 和 TypeLiterals 重构泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114384/

相关文章:

Android:以编程方式更改 View 的绝对位置

oop - 是否有更优雅的方式(或模式)来实现相关类组

java - 通过使用 java Field getType() 方法进行转换,将对象从一种类型转换为另一种类型

c# - 通过反射调用扩展方法(Type.InvokeMember)

android - 如何使用 Android 应用程序重命名 sdcard 上的文件?

visual-studio - 什么是 “Microsoft C++ Visual Runtime Library: Runtime error!”,如何捕获?

scala - "Generic type"和 "Higher-kinded type"有什么区别?

java - 我需要一个自定义通用电源方法

.net - 查找泛型类型

c# - 检查构造函数是否调用另一个构造函数