Manually Register Class in CDI Container

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à.


Following the comments of @AdrianMitev, I finally ended up writing this class which returns an instance of a Managed CDI Bean given its class name (elName) or class type:

public class GetInstance {
    public static Object of(String elName) {
       BeanManager bm = getBeanManager();
       Bean<?> bean = bm.resolve(bm.getBeans(elName));
       return bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean));
    }

    @SuppressWarnings("unchecked")
    public static <T> T of(Class<T> clazz) {
        BeanManager bm = getBeanManager();
        Bean<?> bean = bm.resolve(bm.getBeans(clazz));
        return (T) bm.getReference(bean, bean.getBeanClass(), bm.createCreationalContext(bean));
    }

    private static BeanManager getBeanManager() {
        try {
            return (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

So, if you have a class like this one:

@Named
public class FooClass {
...
}

You can get an a managed CDI instance using:

FooClass fC = GetInstance.of(FooClass.class);

or using its elName

FooClass fC = (FooClass) GetInstance.of("fooClass");

or you can select the name to use:

@Named(value="CustomFooClassName")
public class FooClass {
...
}

And using:

FooClass fC = (FooClass) GetInstance.of("CustomFooClassName");

Tags:

Java

Cdi