Reconstruct generic types at runtime using Guice through types and TypeLiterals

I have several types similar to

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

How can I recreate Foo so that you can use it in Guice? The bit I'm stuck on is how to cross reference K from Bar to the second parameterized type Foo.

So for example

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

Actually this seems wrong, since basically:

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

This is not the same as:

Foo<V extends Bar<K>, K>

As in the latter case, I know that K is a consistent type.

Any ideas?

Greetings

Matt

+3
source share
2 answers

From JavaDoc for Binder :

, Set<E> all .

Foo, K V. 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);
}

, :

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

Guice factory TypeVariable. , .

, Guice , . , Map<String, Integer>, Map<K, V>.

0

Source: https://habr.com/ru/post/1712387/


All Articles