Java Reflection Generic Type from Class getGenericClass(final Method method)

Here you can find the source of getGenericClass(final Method method)

Description

get Generic Class

License

Open Source License

Declaration

@SuppressWarnings("rawtypes")
    public static Class getGenericClass(final Method method) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.*;

public class Main {
    @SuppressWarnings("rawtypes")
    public static Class getGenericClass(final Method method) {
        final Type returnType = method.getGenericReturnType();
        return getActualType(returnType, 0);

    }/*from w  w  w  .  j a  va  2  s  . c o  m*/

    public static Class<?> getActualType(Type genericType, int pos) {

        if (genericType == null) {
            return null;
        }
        if (!ParameterizedType.class.isAssignableFrom(genericType.getClass())) {
            if (genericType instanceof TypeVariable) {
                genericType = getType(((TypeVariable<?>) genericType).getBounds(), pos);
            } else if (genericType instanceof WildcardType) {
                WildcardType wildcardType = (WildcardType) genericType;
                Type[] bounds = wildcardType.getLowerBounds();
                if (bounds.length == 0) {
                    bounds = wildcardType.getUpperBounds();
                }
                genericType = getType(bounds, pos);
            }

            Class<?> cls = (Class<?>) genericType;
            return cls.isArray() ? cls.getComponentType() : cls;
        }
        ParameterizedType paramType = (ParameterizedType) genericType;
        Type t = getType(paramType.getActualTypeArguments(), pos);
        return t instanceof Class ? (Class<?>) t : getActualType(t, pos);
    }

    public static Type getType(Type[] types, int pos) {
        if (pos >= types.length) {
            throw new RuntimeException("No type can be found at position " + pos);
        }
        return types[pos];
    }
}

Related

  1. getGenericClass(Class clazz, int index)
  2. getGenericClass(Class cls)
  3. getGenericClass(final Class class1)
  4. getGenericClass(final Class parametrizedClass, int pos)
  5. getGenericClass(final Class parametrizedClass, int pos)
  6. getGenericClass(Object o)
  7. getGenericClass(Object object, int index)
  8. getGenericClass(Object source, ParameterizedType type)
  9. getGenericClass(Type type)