Search code examples
javagenericscdi

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


This is the way how I get manually instance of cdi bean:

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

if I declare Foo class this way:

@Dependent
public class Foo{
   ...
}

everything works. However, if I declare class Foo this way

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

cdi container can't create cdi bean. How can I get manually cdi bean of class declared with generics (Foo)?


Solution

  • What you are looking for is probably javax.enterprise.util.TypeLiteral. It is a utility class allowing you to specify a (bean) type along with the type variable. It then allows to retrieve the raw type as well as the actual type parameter inside. Here is a code snippet:

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