Java Reflection Generic Type from Class getGenericClass(Object source, ParameterizedType type)

Here you can find the source of getGenericClass(Object source, ParameterizedType type)

Description

Try to extract the generic type of the given ParameterizedType used in the given source object.

License

Open Source License

Parameter

Parameter Description
source a parameter
type a parameter

Declaration

private static Class getGenericClass(Object source, ParameterizedType type) 

Method Source Code


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

public class Main {
    /**/* ww w .j a  v a2 s  .c  o m*/
     * 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. getGenericClass(final Class parametrizedClass, int pos)
  2. getGenericClass(final Class parametrizedClass, int pos)
  3. getGenericClass(final Method method)
  4. getGenericClass(Object o)
  5. getGenericClass(Object object, int index)
  6. getGenericClass(Type type)
  7. getGenericClassByIndex(Type genericType, int index)
  8. getGenericClassType(Class clazz, Class filterClass)
  9. getGenericDeclaringType(Class baseClass, Class declaringClass)