Java Reflection Generic Type from Class getGenericType(Class clazz)

Here you can find the source of getGenericType(Class clazz)

Description

get Generic Type

License

Apache License

Declaration

public static Class<?> getGenericType(Class<?> clazz) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    private static final Class<?>[] EMPTY_CLASSES = new Class<?>[0];

    public static Class<?> getGenericType(Class<?> clazz) {
        Type genericType = clazz.getGenericInterfaces()[0];
        Class<?>[] classes = getActualClass(genericType);
        if (classes.length == 0) {
            return null;
        } else {//ww w.  j a  va2s . c  om
            return classes[0];
        }
    }

    public static Class<?>[] getActualClass(Type genericType) {

        if (genericType instanceof ParameterizedType) {

            Type[] actualTypes = ((ParameterizedType) genericType).getActualTypeArguments();
            Class<?>[] actualClasses = new Class<?>[actualTypes.length];

            for (int i = 0; i < actualTypes.length; i++) {
                Type actualType = actualTypes[i];
                if (actualType instanceof Class<?>) {
                    actualClasses[i] = (Class<?>) actualType;
                } else if (actualType instanceof GenericArrayType) {
                    Type componentType = ((GenericArrayType) actualType).getGenericComponentType();
                    actualClasses[i] = Array.newInstance((Class<?>) componentType, 0).getClass();
                } else if (actualType instanceof ParameterizedType) {
                    actualClasses[i] = (Class<?>) ((ParameterizedType) actualType).getRawType();
                }
            }

            return actualClasses;
        }

        return EMPTY_CLASSES;
    }
}

Related

  1. getGenericSuperType(Class subclass, Class classWithParameter)
  2. getGenericSuperType(Class class1, Class class2)
  3. getGenericType(Class clazz, int index)
  4. getGenericType(Class propertyType)
  5. getGenericType(Class clazz)
  6. getGenericType(Class clazz, int index)
  7. getGenericType(Class target)
  8. getGenericType(Class type)
  9. getGenericType(Class type, Class clazz)