繁体   English   中英

CDI:手动获取使用泛型声明的类的bean实例

[英]CDI: get manually instance of bean of class which is declared with generics

这是我手动获取cdi bean实例的方式:

Bean<?> bean = (Bean<?>)beanManager.resolve(beanManager.getBeans(Foo.class));
Foo foo=(Foo) beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean));

如果我这样声明Foo类:

@Dependent
public class Foo{
   ...
}

一切正常。 但是,如果我以这种方式声明Foo类

@Dependent
public class Foo<T>{
   ...
}

cdi容器无法创建cdi bean。 如何手动获得用泛型(Foo)声明的类的CDI bean?

您正在寻找的可能是javax.enterprise.util.TypeLiteral 它是一个实用程序类,可让您指定(bean)类型和类型变量。 然后,它允许检索原始类型以及内部的实际类型参数。 这是一个代码片段:

// define the type you want
TypeLiteral<Foo<Bar>> typeLiteral = new TypeLiteral<Foo<Bar>>() {};

// now search for beans; note that getBeans allows to specify Annotations as well!
Set<Bean<?>> beans = beanManager.getBeans(typeLiteral.getType());

// and apply resolution - you should get the one you want here
Bean<?> bean = beanManager.resolve(beans);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM