Java Reflection Generic Type from Field getGenericType(Field field)

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

Description

Gets generic type from field (if field type is ParameterizedType )

License

Apache License

Parameter

Parameter Description
field class field

Return

generic type

Declaration

public static Class<?> getGenericType(Field field) 

Method Source Code


//package com.java2s;
/*-//from  ww w.  ja v a 2s .c o m
 * #%L
 * Bobcat Parent
 * %%
 * Copyright (C) 2016 Cognifide Ltd.
 * %%
 * 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.
 * #L%
 */

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

public class Main {
    /**
     * Gets generic type from field (if field type is {@link ParameterizedType})
     *
     * @param field class field
     * @return generic type
     */
    public static Class<?> getGenericType(Field field) {
        Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            Type firstParameter = ((ParameterizedType) type).getActualTypeArguments()[0];
            if (!(firstParameter instanceof WildcardType)) {
                return (Class<?>) firstParameter;
            }
        }
        return null;
    }
}

Related

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