get Super Class Generic Type - Java Reflection

Java examples for Reflection:Generic

Description

get Super Class Generic Type

Demo Code

/*/* w  ww  . ja v a2s.  co  m*/
 * Copyright 2014-2017 ZuoBian.com All right reserved. This software is the confidential and proprietary information of
 * ZuoBian.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with ZuoBian.com.
 */
//package com.java2s;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    public static Class getSuperClassGenericType(Class clazz) {
        return getSuperClassGenericType(clazz, 0);
    }

    public static Class getSuperClassGenericType(Class clazz, int index) {
        Type genericSuperclass = clazz.getGenericSuperclass();
        if (genericSuperclass == null) {
            return null;
        }
        if ((genericSuperclass instanceof ParameterizedType) == false) {
            return null;
        }
        ParameterizedType paramterizedType = (ParameterizedType) genericSuperclass;
        Type[] actualTypeArguments = paramterizedType
                .getActualTypeArguments();
        if (actualTypeArguments.length < (index - 1)
                || actualTypeArguments.length == 0) {
            return null;
        }
        return (Class) actualTypeArguments[0];
    }
}

Related Tutorials