2 Replies Latest reply on Mar 12, 2012 11:38 AM by Feng Jiang

    CDI - Injecting Classes at runtime

    hamsterdancer Newbie

      Hi there

      I'm working on a project, where it is needed to load some classes at runtime. The classes to load are parts of CDI-Containers and have to be able to inject some stuff. The "loading class" itself is a part of a CDI-Container as well.

      Now comes my problem. It is possible to load and instantiate any class via reflection, but in this case it would not be possible for the classes to be loaded to get anything injected. So it is needed to get an instance of these classes as it would be internally done by the server like when we would use the annotation @javax.inject.Inject.

      Is there any way to load the classes of another CDI-container in a way that they can still work with Injections (otherwise it would not make any sense^^)? Maybe there is any kind of Class which is responsible for for handling all of these classes so that I can simply tell it the name of the class to load (as I would do it with reflections)... ?


        • 2. Re: CDI - Injecting Classes at runtime
          Feng Jiang Newbie

          // Get BeanManager By JNDI

          public static BeanManager getBeanManager() {

                              try {

                                        return (BeanManager) new InitialContext()


                              } catch (NamingException e) {

                                        log.error("Can not get BeanManager!");



                              return null;



          // Get the cls's instance

          public static <T> T getBeanReference(Class<T> cls) {

                              Bean<?> myBean = getBeanManager().getBeans(cls).iterator().next();

                              return (T) getBeanManager().getReference(myBean, cls,




          // Get the instance which with Annotation a

          public static <T> T getBeanReference(Class<T> cls, final Class a) {


                              Bean<?> myBean = getBeanManager()

                                                  .getBeans(cls, new AnnotationLiteral() {


                                                            public Class annotationType() {

                                                                      return a;



                              return (T) getBeanManager().getReference(myBean, cls,






          I hope above three method will help you