Java Reflection Generic Type from Field getGenericMultivalueType(final Field p)

Here you can find the source of getGenericMultivalueType(final Field p)

Description

Returns the generic class of multi-value objects.

License

Apache License

Parameter

Parameter Description
p Field to examine

Return

The Class of generic type if any, otherwise null

Declaration

public static Class<?> getGenericMultivalueType(final Field p) 

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.Map;

public class Main {
    /**/*from  w  w w.  ja v a2  s  . c  o  m*/
     * Returns the generic class of multi-value objects.
     * 
     * @param p
     *          Field to examine
     * @return The Class<?> of generic type if any, otherwise null
     */
    public static Class<?> getGenericMultivalueType(final Field p) {
        if (p.getType() instanceof Class<?>) {
            final Type genericType = p.getGenericType();
            if (genericType != null
                    && genericType instanceof ParameterizedType) {
                final ParameterizedType pt = (ParameterizedType) genericType;
                if (pt.getActualTypeArguments() != null
                        && pt.getActualTypeArguments().length > 0) {
                    if (((Class<?>) pt.getRawType())
                            .isAssignableFrom(Map.class)) {
                        if (pt.getActualTypeArguments()[1] instanceof Class<?>) {
                            return (Class<?>) pt.getActualTypeArguments()[1];
                        } else if (pt.getActualTypeArguments()[1] instanceof ParameterizedType)
                            return (Class<?>) ((ParameterizedType) pt
                                    .getActualTypeArguments()[1])
                                    .getRawType();
                    } else if (pt.getActualTypeArguments()[0] instanceof Class<?>) {
                        return (Class<?>) pt.getActualTypeArguments()[0];
                    } else if (pt.getActualTypeArguments()[0] instanceof ParameterizedType)
                        return (Class<?>) ((ParameterizedType) pt
                                .getActualTypeArguments()[0]).getRawType();
                }
            } else if (p.getType().isArray())
                return p.getType().getComponentType();
        }
        return null;
    }
}

Related

  1. getGenericFieldClassType(Class clz, String propertyName)
  2. getGenericFieldType(Field field, boolean isAllowNull)
  3. getGenericFieldType(Object target, String fieldName)
  4. getGenericFieldTypeFromPosition(Field field, int position)
  5. getGenericlyTypeCount(Field field)
  6. getGenericMultivalueType(final Field p)
  7. getGenericParameterClass(Field field)
  8. getGenericParameterClass(Field field)
  9. getGenericParameters(Field f)