get Instance By Type from BeanManager - Java Reflection

Java examples for Reflection:Java Bean

Description

get Instance By Type from BeanManager

Demo Code


import java.lang.annotation.Annotation;
import java.util.Collection;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;

public class Main{
    public final static <T> T getInstanceByType(final BeanManager manager,
            final Class<T> type) {
        try {//from   w w w .  ja  v  a  2 s .  c  o  m
            final Bean<?> bean = manager.resolve(manager.getBeans(type));
            CreationalContext<?> ctx = manager
                    .createCreationalContext(bean);
            if (bean != null) {
                return type.cast(manager.getReference(bean, type, ctx));
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials