Java Reflection Generic Type from Field getGenericType(Field field)

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

Description

Returns the generic type of an field.

License

Apache License

Parameter

Parameter Description
field - The field.

Return

The class type.

Declaration

public static Class<?> getGenericType(Field field) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2010-2011 Hannes Niederhausen, Topic Maps Lab
 * /*from www.  j av a  2 s .c  o m*/
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

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

public class Main {
    /**
     * Returns the generic type of an field.
     * @param field - The field.
     * @return The class type.
     */
    public static Class<?> getGenericType(Field field) {

        Type type = field.getGenericType();

        return getGenericType(type);
    }

    /**
     * Returns the generic type of an type.
     * @param type - The type.
     * @return The class type.
     */
    public static Class<?> getGenericType(Type type) {

        if (type instanceof ParameterizedType) {

            ParameterizedType pt = (ParameterizedType) type;
            Type[] args = pt.getActualTypeArguments();

            for (Type typeArg : args) {

                Class<?> typeArgClass = (Class<?>) typeArg;

                return typeArgClass;
            }
        } else if (((Class<?>) type).isArray()) {

            return ((Class<?>) type).getComponentType();

        }

        return (Class<?>) type;

    }
}

Related

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