Java Reflection Generic Type from Class getGenericTypeOfInterface(Class clazz, Class specificInterface)

Here you can find the source of getGenericTypeOfInterface(Class clazz, Class specificInterface)

Description

Fetches the declared type on a specific interface implemented by the provided class.

License

Open Source License

Parameter

Parameter Description
clazz the class on which implemented interfaces will be looked upon
specificInterface the interface to look for

Return

the generic type implemented for the provided interface, or null if not found.

Declaration

public static Class<?> getGenericTypeOfInterface(Class<?> clazz, Class<?> specificInterface) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//  w w w.  j a  v a2  s.  c om
     * Fetches the declared type on a specific interface implemented by the provided class.
     * @param clazz the class on which implemented interfaces will be looked upon
     * @param specificInterface the interface to look for
     * @return the generic type implemented for the provided interface, or null if not found.
     */
    public static Class<?> getGenericTypeOfInterface(Class<?> clazz, Class<?> specificInterface) {
        Type[] genericInterfaces = clazz.getGenericInterfaces();
        if (genericInterfaces != null) {
            for (Type genericType : genericInterfaces) {
                if (genericType instanceof ParameterizedType) {
                    Type rawType = ((ParameterizedType) genericType).getRawType();
                    if (rawType.equals(specificInterface)) {
                        ParameterizedType paramType = (ParameterizedType) genericType;
                        return (Class<?>) paramType.getActualTypeArguments()[0];
                    }
                }
            }
        }
        return null;
    }
}

Related

  1. getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class baseRequested)
  2. getGenericTypeArgumentsOfInheritedType(final Object object, final Class inheritedType)
  3. getGenericTypeClass(Class clazz, int index)
  4. getGenericTypeClasses(List> genericTypeClasses, Type... genericTypes)
  5. getGenericTypeForMapProperty(Class javaClass, String propertyName, boolean isKeyType)
  6. getGenericTypeOfParameter(Class clazz, String method, int parameterIndex)
  7. getGenericTypeParameter(Class aClass, Class genericClass, int index)
  8. getGenericTypes(Class c)
  9. getGenericTypes(Class clazz)