How to retrieve class of generic argument in a CDI producer?

こ雲淡風輕ζ 提交于 2019-12-25 06:57:48

问题


I have a Java class with a generic type. In the business logic of that class, I need to refer to the Class object of the generic type. Therefore, the constructor get the Class object passed as argument:

public class MyClass<GENERIC_TYPE>{
    private Class<GENERIC_TYPE> genericTypeClass;

    public MyClass(Class<GENERIC_TYPE> genericTypeClass){
        this.genericTypeClass=genericTypeClass;
    }
}

I create the instance(s) of this class using a CDI producer, whose squeleton looks like

public class MyClassProducer{
    @Produces
    MyClass<GENERIC_TYPE> createMyClass(InjectionPoint injectionPoint){
        Class<GENERIC_TYPE> genericTypeClass = ????
        return new MyClass(genericTypeClass);
    }
}

How do I retrieve genericTypeClass ?


回答1:


Solution is a two liner:

public class MyClassProducer {
    @Produces
    <GENERIC_TYPE> MyClass<GENERIC_TYPE> createMyClass(InjectionPoint injectionPoint){
        final ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType();
        final Class<GENERIC_TYPE> genericTypeClass = 
            (Class<GENERIC_TYPE>) parameterizedType.getActualTypeArguments()[0];
        return new MyClass(genericTypeClass);
    }
}


来源:https://stackoverflow.com/questions/36833292/how-to-retrieve-class-of-generic-argument-in-a-cdi-producer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!