Java Reflection Generic Type from Field getGenericFieldType(Field field, boolean isAllowNull)

Here you can find the source of getGenericFieldType(Field field, boolean isAllowNull)

Description

Returns the generic type parameter of a return value by a field.

License

Open Source License

Parameter

Parameter Description
field field or null if method
isAllowNull whether null is allowed as a return value or expected Object.class

Return

generic type parameter

Declaration

public static Class getGenericFieldType(Field field, boolean isAllowNull) 

Method Source Code

//package com.java2s;
/**************************************************************************************
 * Copyright (C) 2008 EsperTech, Inc. All rights reserved.                            *
 * http://esper.codehaus.org                                                          *
 * http://www.espertech.com                                                           *
 * ---------------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the GPL license       *
 * a copy of which has been included with this distribution in the license.txt file.  *
 **************************************************************************************/

import java.lang.reflect.*;

public class Main {
    /**/*from w w w .j  av  a 2s  .c om*/
     * Returns the generic type parameter of a return value by a field.
     * @param field field or null if method
     * @param isAllowNull whether null is allowed as a return value or expected Object.class
     * @return generic type parameter
     */
    public static Class getGenericFieldType(Field field, boolean isAllowNull) {
        Type t = field.getGenericType();
        Class result = getGenericType(t, 0);
        if (!isAllowNull && result == null) {
            return Object.class;
        }
        return result;
    }

    public static Class getGenericType(Type t, int index) {
        if (t == null) {
            return null;
        }
        if (!(t instanceof ParameterizedType)) {
            return null;
        }
        ParameterizedType ptype = (ParameterizedType) t;
        if ((ptype.getActualTypeArguments() == null) || (ptype.getActualTypeArguments().length < (index + 1))) {
            return Object.class;
        }
        Type typeParam = ptype.getActualTypeArguments()[index];
        if (!(typeParam instanceof Class)) {
            return Object.class;
        }
        return (Class) typeParam;
    }
}

Related

  1. getGenericArgument(Field field, int index)
  2. getGenericClass(Field f, int n)
  3. getGenericClasses(Field field)
  4. getGenericElementType(Field field)
  5. getGenericFieldClassType(Class clz, String propertyName)
  6. getGenericFieldType(Object target, String fieldName)
  7. getGenericFieldTypeFromPosition(Field field, int position)
  8. getGenericlyTypeCount(Field field)
  9. getGenericMultivalueType(final Field p)