Java Utililty Methods Reflection Generic Return Type

List of utility methods to do Reflection Generic Return Type

Description

The list of methods to do Reflection Generic Return Type are organized into topic(s).

Method

ClassgetGenericClassFromMethodReturn(Method m)
get Generic Class From Method Return
Type type = m.getGenericReturnType();
if (type instanceof ParameterizedType) {
    ParameterizedType pt = (ParameterizedType) type;
    return (Class) pt.getActualTypeArguments()[0];
return null;
ClassgetGenericReturnClass(Method method)
get Generic Return Class
Class returnClazz = method.getReturnType();
Type genType = method.getGenericReturnType();
if (genType instanceof ParameterizedType) {
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if ((params != null) && (params.length >= 0)) {
        returnClazz = (Class) params[0];
return returnClazz;
ClassgetGenericReturnType(Method m)
get Generic Return Type
Type t = m.getGenericReturnType();
if (t instanceof ParameterizedType) {
    for (Type arg : ((ParameterizedType) t).getActualTypeArguments()) {
        return (Class) arg;
return null;
ClassgetGenericReturnTypeMap(Method method, boolean isAllowNull)
Returns the second generic type parameter of a return value by a field or method.
Type t = method.getGenericReturnType();
Class result = getGenericType(t, 1);
if (!isAllowNull && result == null) {
    return Object.class;
return result;
TypegetGenericReturnTypeOfGenericInterfaceMethod(Class clazz, Method method)
Given an interface Method, look in the implementing class for the method that implements the interface's method to obtain generic type information.
if (!method.getDeclaringClass().isInterface()) {
    return method.getGenericReturnType();
try {
    Method tmp = clazz.getMethod(method.getName(), method.getParameterTypes());
    return tmp.getGenericReturnType();
} catch (NoSuchMethodException e) {
return method.getGenericReturnType();
TypegetGenericReturnTypeOfGenericInterfaceMethod(Class clazz, Method method)
get Generic Return Type Of Generic Interface Method
if (!method.getDeclaringClass().isInterface()) {
    return method.getGenericReturnType();
try {
    Method tmp = clazz.getMethod(method.getName(), method.getParameterTypes());
    return tmp.getGenericReturnType();
} catch (NoSuchMethodException e) {
return method.getGenericReturnType();
ClassgetGenericType(Type returnType, int index)
get Generic Type
if (returnType instanceof ParameterizedType) {
    ParameterizedType type = (ParameterizedType) returnType;
    Type[] typeArguments = type.getActualTypeArguments();
    if (index >= typeArguments.length || index < 0) {
        throw new RuntimeException("invalid index : " + index);
    return (Class) typeArguments[index];
return (Class) returnType;