How to get the class of type variable in Java Generics

前端 未结 7 1444
北恋
北恋 2021-02-01 17:24

I\'ve seen similar questions but they didnt help very much.

For instance I\'ve got this Generic Class:

public class ContainerTest
{

    public          


        
7条回答
  •  太阳男子
    2021-02-01 18:11

    If you are interested in the reflection way, I found a partial solution in this great article: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

    In short, you can use java.lang.Class.getGenericSuperclass() and java.lang.reflect.ParameterizedType.getActualTypeArguments() methods, but you have to subclass some parent super class.

    Following snippet works for a class that directly extends the superclass AbstractUserType. See the referenced article for more general solution.

    import java.lang.reflect.ParameterizedType;
    
    
    public class AbstractUserType {
    
        public Class returnedClass() {
            ParameterizedType parameterizedType = (ParameterizedType) getClass()
                    .getGenericSuperclass();
    
            @SuppressWarnings("unchecked")
            Class ret = (Class) parameterizedType.getActualTypeArguments()[0];
    
            return ret;
        }
    
        public static void main(String[] args) {
            AbstractUserType myVar = new AbstractUserType() {};
    
            System.err.println(myVar.returnedClass());
        }
    
    }
    

提交回复
热议问题