Java Reflection Method Get from Object getMethodReturnTypeGeneric(Object source, Method method)

Here you can find the source of getMethodReturnTypeGeneric(Object source, Method method)

Description

Tries to retrieve the generic parameter of an ObjectProperty return by a method at runtime.

License

Open Source License

Declaration

public static Class getMethodReturnTypeGeneric(Object source, Method method) 

Method Source Code


//package com.java2s;
import java.lang.reflect.*;

public class Main {
    /**//ww  w . java 2 s . co m
     * Tries to retrieve the generic parameter of an ObjectProperty return by a method at runtime.
     */
    public static Class getMethodReturnTypeGeneric(Object source, Method method) {
        Type type = method.getGenericReturnType();
        if (type instanceof ParameterizedType) {
            return getGenericClass(source, (ParameterizedType) type);
        } else {
            return method.getReturnType();
        }
    }

    /**
     * Try to extract the generic type of the given ParameterizedType used in the given source object.
     *
     * @param source
     * @param type
     * @return
     */
    private static Class getGenericClass(Object source, ParameterizedType type) {
        Type type1 = type.getActualTypeArguments()[0];
        if (type1 instanceof ParameterizedType) {
            return (Class) ((ParameterizedType) type1).getRawType();
        } else if (type1 instanceof TypeVariable) {
            // Type is generic, try to get its actual type from the super class
            // e.g.: ObjectProperty<T> where T extends U
            if (source.getClass().getGenericSuperclass() instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) source.getClass().getGenericSuperclass())
                        .getActualTypeArguments()[0];
            } else {
                // The actual type is not declared, use the upper bound of the type e.g. U
                return (Class) ((TypeVariable) type1).getBounds()[0];
            }
        } else {
            return (Class) type1;
        }
    }
}

Related

  1. getMethodNames(Object obj, boolean includeInheritedMethods)
  2. getMethodObject(Class type, Class clazz, String method, Class[] args, Object object, Object[] objects)
  3. getMethodObject(Object object, String method, Object[] parametre)
  4. getMethodResult(final Object element, final String methodName)
  5. getMethodReturn(String className, String methodName, Class[] params, Object[] args, boolean isStatic)
  6. getMethods(Class objectClass, Class annotationClass)
  7. getMethods(Object instance, String name, Class[] arguments, boolean isPrefix)
  8. getMethods(Object obj, boolean hasParent)
  9. getMethods(Object obj, int cmpModifier, String prefix)