The answer was very close, but I did not pay attention to it. Yes, you can get an instance of the bean class of any bean contained in any of the active contexts (associated with the current thread) using BeanManager. This method does the job:
public static <B> B getContextualBeanInstance(Class<B> type, Annotation... qualifiers) { try { BeanManager beanManager = InitialContext.doLookup("java:comp/BeanManager"); Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers); Bean<?> bean = beanManager.resolve(beans); CreationalContext<?> cc = beanManager.createCreationalContext(bean); return (B) beanManager.getReference(bean, type, cc); } catch (NamingException e) { throw new RuntimeException("", e); } }
The only difference from the method that I mentioned in the question column is that instead of Bean#create(..) , BeanManager#getReference(..) .
If you want to support parameterized bean types, change the type parameter type from Class<B> to type .
If the bean is dependent on @Dependent, you should take care to destroy the bean class instance to avoid memory leaks. Here I will explain how to do it.
source share