Java Reflection Generic Type from Class getGenericSuperType(Class class1, Class class2)

Here you can find the source of getGenericSuperType(Class class1, Class class2)

Description

for example when class1 is EpochDateConverter which implements TypeConverter, and class2 is TypeConverter, the return value is Date.class

License

Apache License

Parameter

Parameter Description
class1 a parameter
class2 a parameter

Declaration

@SuppressWarnings("restriction")
public static Type getGenericSuperType(Class<?> class1, Class<?> class2) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Type;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

public class Main {
    /**/* www .  j  a v a2 s  .c  o  m*/
     * for example when class1 is EpochDateConverter which implements
     * TypeConverter<Date>, and class2 is TypeConverter, the return value is
     * Date.class
     * 
     * @param class1
     * @param class2
     * @return
     */
    @SuppressWarnings("restriction")
    public static Type getGenericSuperType(Class<?> class1, Class<?> class2) {
        if (class1 == null || class2 == null)
            throw new RuntimeException("null value");
        List<Type> genericSupers = new ArrayList<Type>();
        genericSupers.add(class1.getGenericSuperclass());
        genericSupers.addAll(newArrayList(class1.getGenericInterfaces()));

        for (Type type : genericSupers) {
            if (type instanceof ParameterizedTypeImpl) {
                ParameterizedTypeImpl a = (ParameterizedTypeImpl) type;
                if (a.getRawType() == class2)
                    return a.getActualTypeArguments()[0];
            }
        }

        return null;
    }

    public static <E> ArrayList<E> newArrayList(E... elements) {
        ArrayList<E> list = new ArrayList<E>(elements.length);
        Collections.addAll(list, elements);
        return list;
    }
}

Related

  1. getGenericSuperclass(Class clazz)
  2. getGenericSuperclass(Class cls)
  3. getGenericSuperclassActualTypes(Collection types, Class aClass)
  4. getGenericSuperType(Class clz, int index)
  5. getGenericSuperType(Class subclass, Class classWithParameter)
  6. getGenericType(Class clazz, int index)
  7. getGenericType(Class propertyType)
  8. getGenericType(Class clazz)
  9. getGenericType(Class clazz)