Java Reflection Generic Type from Class getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex)

Here you can find the source of getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex)

Description

get Generic Argument Type

License

Open Source License

Declaration

public static Class getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex) 

Method Source Code


//package com.java2s;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    public static Class getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex) {
        Type superType = currentClass.getGenericSuperclass();
        if (superType == null) {
            throw new IllegalArgumentException(
                    "Class '" + currentClass + "' doesn't have correct generic super class");
        }/*ww w. ja  va  2 s. c o  m*/
        if (!(superType instanceof ParameterizedType)
                || genericSuperClass != null && ((ParameterizedType) superType).getRawType() != genericSuperClass) {
            return getGenericArgumentType(currentClass.getSuperclass(), genericSuperClass, argumentIndex);
        }
        Object[] args = ((ParameterizedType) superType).getActualTypeArguments();
        if (argumentIndex >= args.length) {
            throw new IllegalArgumentException("Invalid argument index: " + argumentIndex);
        }
        return cast(Class.class, args[argumentIndex]);
    }

    public static Class getGenericArgumentType(Class currentClass, Class genericSuperClass) {
        return getGenericArgumentType(currentClass, genericSuperClass, 0);
    }

    public static Class getGenericArgumentType(Class currentClass, int argumentIndex) {
        return getGenericArgumentType(currentClass, null, argumentIndex);
    }

    public static Class getGenericArgumentType(Class currentClass) {
        return getGenericArgumentType(currentClass, null, 0);
    }

    @SuppressWarnings("unchecked")
    public static <T> T cast(Class<T> clazz, Object object) {
        if (clazz.isAssignableFrom(object.getClass())) {
            return clazz.cast(object);
        }
        throw new ClassCastException("Cannot cast class " + object.getClass().getName() + ", whose classloader is "
                + object.getClass().getClassLoader() + ", to class " + clazz + ", whose classloader is "
                + clazz.getClassLoader());
    }
}

Related

  1. getGenericArgumentType(Class clazz)
  2. getGenericClass(Class clazz)
  3. getGenericClass(Class clazz)
  4. getGenericClass(Class clazz)
  5. getGenericClass(Class clazz, int index)