Java Reflection Generic Type from Field getGenericsTypeFromCollectionField(Field field)

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

Description

Gets generics info despite runtime type erasure.

License

Apache License

Parameter

Parameter Description
field Field

Return

Class (if found) or null if not

Declaration

public static Class<?> getGenericsTypeFromCollectionField(Field field) 

Method Source Code

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

import java.lang.reflect.Field;

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

import java.util.List;

import java.util.Set;

public class Main {
    /**//from w w  w . ja  va 2s.c o  m
     * Gets generics info despite runtime type erasure. Hack alert, obviously.
     * @param field Field
     * @return Class (if found) or null if not
     */
    public static Class<?> getGenericsTypeFromCollectionField(Field field) {
        Class<?> clazz = null;
        if (List.class.isAssignableFrom(field.getType()) || Set.class.isAssignableFrom(field.getType())) {
            field.setAccessible(true);
            ParameterizedType ptype = (ParameterizedType) field.getGenericType();
            Type[] types = ptype.getActualTypeArguments();
            if (types != null && types.length > 0) {
                clazz = (Class<?>) types[0];
            }
        }
        return clazz;
    }
}

Related

  1. getGenericParameterClass(Field field)
  2. getGenericParameterClass(Field field)
  3. getGenericParameters(Field f)
  4. getGenericParametersInternal(Type genericFieldType)
  5. getGenericReturnType(Method method, Field field, boolean isAllowNull)
  6. getGenericType(Field field)
  7. getGenericType(Field field)
  8. getGenericType(Field field)
  9. getGenericType(Field field)