Java Reflection Generic Type from Field getGenericType(Field field)

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

Description

Similar to #getGenericType(Type[]) but only for fields

License

Open Source License

Parameter

Parameter Description
field The field

Return

The class of the generic type

Declaration

public static Class<?> getGenericType(Field field) 

Method Source Code

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

import java.lang.reflect.*;
import java.util.*;

public class Main {
    public static Class<?> getGenericType(Type[] genericParameterTypes) {
        List<Class<?>> l = getGenericTypes(genericParameterTypes);
        if (l.size() == 0)
            return Void.TYPE;
        return l.get(0);
    }/*  w  ww  .  j  a  va 2 s  .  c  o m*/

    /**
     * Similar to {@link #getGenericType(Type[])} but only for fields
     *
     * @param field The field
     * @return The class of the generic type
     */
    public static Class<?> getGenericType(Field field) {
        return (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
    }

    /**
     * Returns a list of class's for every generic parameter type
     * given by {@link Method#getGenericParameterTypes()} or {@link Class#getGenericInterfaces()}
     *
     * @param genericParameterTypes The genericParameterTypes mentioned above
     * @return The list of types as class's
     * @see #getGenericType(Type[])
     */
    public static List<Class<?>> getGenericTypes(Type[] genericParameterTypes) {
        List<Class<?>> l = new ArrayList<>();
        if (genericParameterTypes == null)
            return l;

        try {
            for (Type t : genericParameterTypes) {
                ParameterizedType pType = (ParameterizedType) t;
                for (Type type : pType.getActualTypeArguments()) {
                    l.add((Class<?>) type);
                }
            }
        } catch (Exception e) {
            // couldn't fetch them .. just returning an empty list ..
            return new ArrayList<>();
        }
        return l;
    }
}

Related

  1. getGenericReturnType(Method method, Field field, boolean isAllowNull)
  2. getGenericsTypeFromCollectionField(Field field)
  3. getGenericType(Field field)
  4. getGenericType(Field field)
  5. getGenericType(Field field)
  6. getGenericType(Field field)
  7. getGenericType(Field field)
  8. getGenericType(Type type, Type fieldType)
  9. getGenericTypeArguments(final Field field)