Java Reflection Generic Type from Class getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class baseRequested)

Here you can find the source of getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class baseRequested)

Description

Looks if generic supertype is paramized with given baseRequested.

License

Apache License

Parameter

Parameter Description
T the generic type
genericSuperclass the generic superclass
baseRequested the base requested

Return

the generic type argument from generic super type. null if not found.

Declaration


public static <T> Class<T> getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass,
        Class<T> baseRequested) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

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

public class Main {
    /**//from w  ww . j ava 2  s  .  co m
     * Looks if generic supertype is paramized with given baseRequested.
     *
     * @param <T> the generic type
     * @param genericSuperclass the generic superclass
     * @param baseRequested the base requested
     * @return the generic type argument from generic super type. null if not found.
     */
    //CHECKSTYLE.OFF FinalParameter Precondition cast
    public static <T> Class<T> getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass,
            Class<T> baseRequested) {
        Type loopVar = genericSuperclass;
        while (loopVar != null && !(ParameterizedType.class.isAssignableFrom(loopVar.getClass()))) {
            loopVar = ((Class<?>) loopVar).getGenericSuperclass();
        }
        if (loopVar != null && ParameterizedType.class.isAssignableFrom(loopVar.getClass())) {
            Type[] typeArgs = ((ParameterizedType) loopVar).getActualTypeArguments();
            for (Type typeArg : typeArgs) {
                if (typeArg instanceof ParameterizedType) {
                    typeArg = ((ParameterizedType) typeArg).getRawType();
                }
                if ((typeArg instanceof Class) == false) {
                    continue;
                }
                if (baseRequested.isAssignableFrom((Class<?>) typeArg) == false) {
                    continue;
                }
                return (Class<T>) typeArg;
            }
        }
        return null;
    }
}

Related

  1. getGenericType(Class type)
  2. getGenericType(Class type, Class clazz)
  3. getGenericType(Object o, Class declaringClass, int idx)
  4. getGenericType(Type type, Class rawType, int index)
  5. getGenericTypeArgument(Class clazz, int index)
  6. getGenericTypeArgumentsOfInheritedType(final Object object, final Class inheritedType)
  7. getGenericTypeClass(Class clazz, int index)
  8. getGenericTypeClasses(List> genericTypeClasses, Type... genericTypes)
  9. getGenericTypeForMapProperty(Class javaClass, String propertyName, boolean isKeyType)