Search code examples
javacdi

Manually Register Class in CDI Container


I have a group of classes which are instantiated by reflection, hence these are not managed by the CDI container, and no injections are made by the context. My question is, is there any way to register these classes in the CDI context, so the classes get managed by the context?

Bellow, is how I create the classes:

String clazz = "org.myorg.thisIsMyClass";
MyClass myClass = Class.forName(clazz).newInstance(); // myClass instance not managed by CDI

How do I make the instance of myClass managed by the CDI container?


Solution

  • If your classes were registered as bean by the container you can use programmatic lookup to get them easily.

    @Inject
    @Any
    Instance<Object> myBeans;
    
    public Object getMyBeanFromClassName(String className) throws Exception{    
        Class clazz = Class.forName(className);
        return myBeans.select(clazz).get();  
    }
    

    Et voilà.