2

Given the type:

public interface Foo<T, X extends A>{...}

I need to use programmatic lookup to find bean that implement the given interface regardless of parameter types. Because of type safe resolution this returns an empty set:

final Set<Bean<?>> foos= BeanManagerProvider.getInstance().getBeanManager().getBeans(Foo.class, new AnyLit());

or via Deltaspike:

org.apache.deltaspike.core.api.provider.BeanProvider.getDependent(Foo.class, new AnyLit())

where AnyLit is:

private static class AnyLit extends AnnotationLiteral<Any> implements Any
{

}

Is there any way to get around this?

Thanks

4

2 回答 2

2

我认为您可以使用TypeLiteral- 一个特殊的 CDI 类,它可以保存类型及其参数。通过这个,您可以大致以这种方式指定您想要的内容:

TypeLiteral<Foo<Object, Object>> typeLiteral = new TypeLiteral<Foo<Object, Object>>() {};
BeanManager bm; //assuming you can retrieve BM somehow
bm.getBeans(typeLiteral.getType(), new AnyLit());

现在,这(我希望)符合CDI 可分配性规则警告:前面的泛型,阅读前喝杯咖啡)。简而言之,您想Object用作一种类型,以便:

  • 它查找所有其他类型,例如 bar <Bar>(都可以分配给Object
  • 参数,例如FooImpl<T> implements Foo<T>也将分配给Object
  • 它还可以找到原始类型的 bean,例如MyFoo implements Foo
于 2017-06-21T12:22:56.570 回答
0

查看Instance容器提供的 bean 并执行以下操作:

@Any
@Inject
private Instance<MyInterface<?>> myParametrizedInterfaces;

Instancebean 是一个Iterable,这意味着您可以遍历所有实现上述接口的bean

注意?泛型参数。在这种情况下,所有泛型参数都将匹配(java 泛型)

于 2017-06-21T16:19:06.033 回答