Finds the generic type declared on a single interface implemented by the provided class. - Java Reflection

Java examples for Reflection:Generic

Description

Finds the generic type declared on a single interface implemented by the provided class.

Demo Code


//package com.java2s;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    /**/*from   w w  w .j  av  a  2s . c o  m*/
     * Finds the generic type declared on a single interface implemented by the provided class.
     * @param clazz the class on which we want to find the generic type.
     * @return the actual type declared on the provided generic interface.
     */
    public static Class<?> getDeclaredGenericType(Class<?> clazz,
            Class<?> genericInterface) {
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        for (Type genericType : genericInterfaces) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) genericType;
                if (paramType.getRawType().equals(genericInterface)) {
                    return (Class<?>) paramType.getActualTypeArguments()[0];
                }
            }
        }
        return null;
    }
}

Related Tutorials