Java Reflection Generic Type from Field getGenericType(Field field)

Here you can find the source of getGenericType(Field field)

Description

get Generic Type

License

Apache License

Declaration

public static Class<?> getGenericType(Field field) 

Method Source Code

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

import java.lang.reflect.*;

public class Main {
    public static Class<?> getGenericType(Field field) {
        ParameterizedType type = (ParameterizedType) field.getGenericType();
        return (Class<?>) type.getActualTypeArguments()[0];
    }/*from   w w  w  .jav  a 2  s. c  o  m*/

    public static <T> Class<T> getActualTypeArguments(Class<?> clazz, int indexOfArgument) {
        Class<T> resolvedType = getActualTypeArguments(clazz.getSuperclass().getGenericSuperclass(),
                indexOfArgument);
        if (resolvedType == null) {
            return getActualTypeArguments(clazz.getGenericSuperclass(), indexOfArgument);
        }
        return resolvedType;
    }

    @SuppressWarnings("unchecked")
    public static <T> Class<T> getActualTypeArguments(Type type, int indexOfArgument) {
        if (type instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) type;
            Type typeArgument = paramType.getActualTypeArguments()[indexOfArgument];
            if (typeArgument instanceof Class<?>) {
                return (Class<T>) typeArgument;
            }
        }
        return null;
    }
}

Related

  1. getGenericType(Field field)
  2. getGenericType(Field field)
  3. getGenericType(Field field)
  4. getGenericType(Field field)
  5. getGenericType(Field field)
  6. getGenericType(Type type, Type fieldType)
  7. getGenericTypeArguments(final Field field)
  8. getGenericTypeOfCollectionField(Field field)
  9. getGenericTypes(Field field)