Guice SPI: find wildcard bindings

Guice provides a tool to find all the bindings for a given type ( Injector # findBindingsByType ), and also provides a TypeLiteral class from which it is possible to create a wildcard. What I would like to do is find all the bindings for some type that is parameterized by a wildcard type, but I cannot figure out how to do this. A look at guice src suggests that I could bark the wrong tree, but I decided that I would ask anyway ... so, for example, I gave a type

Foo<E extends Bar>
BarImplOne implements Bar
BarImplTwo implements Bar

and some type bindings

bind(new TypeLiteral<Foo<BarImplOne>>() {}).to(MyFooOne.class);
bind(new TypeLiteral<Foo<BarImplTwo>>() {}).to(MyFooTwo.class);

then I want to be able to detect both bindings with something like

Injector.findBindingsByType(TypeLiteral.get(Types.newParameterizedType(Foo.class, Types.subtypeOf(Bar.class))));

Any ideas?

Cheers Matt

+3
1

, API, , TypeLiteral . . - , :

for (Map.Entry<Key<?>, Binding<?>> entry 
    : injector.getBindings().entrySet()) {
  Type type = entry.getKey().getTypeLiteral().getType();
  if (!(type instanceof ParameterizedType)) continue;

  ParameterizedType parameterized = (ParameterizedType) type;
  if (parameterizedType.getRawType() != Foo.class) continue;

  Type parameter = .getActualTypeArguments()[0]
  if (!(parameter instanceof Class)) continue;

  Class<?> parameterClass = (Class<?>) parameter;
  if (!Bar.class.isAssignableFrom(parameterClass)) continue;

  results.add(entry);
}

, -, API. Guice, TypeLiteral.isAssignableFrom(TypeLiteral). , !

+3

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


All Articles