Java Reflection Generic Type getGenericType(Type genType, int index)

Here you can find the source of getGenericType(Type genType, int index)

Description

get Generic Type

License

Apache License

Declaration

public static Class getGenericType(Type genType, int index) 

Method Source Code

//package com.java2s;
/*/*from w w w. j  a v a  2 s .c o  m*/
 * Copyright (c) 2015-2020, Chen Rui
 *
 * 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.ParameterizedType;
import java.lang.reflect.Type;

public class Main {

    public static Class getGenericType(Type genType, int index) {
        if (!(genType instanceof ParameterizedType)) {
            while (!Object.class.equals(genType) && !(genType instanceof ParameterizedType)) {
                genType = ((Class) genType).getGenericSuperclass();
            }

            if (Object.class.equals(genType)) {
                return Object.class;
            }
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            //log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            //log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }
        return (Class) params[index];
    }
}

Related

  1. getGenericSuperType(Type t)
  2. getGenericType(@Nullable Type genericType)
  3. getGenericType(Member member, int index)
  4. getGenericType(Method setter)
  5. getGenericType(Object target)
  6. getGenericType(Type t, int index)
  7. getGenericType(Type type)
  8. getGenericTypeArguments(Method m, int i)
  9. getGenericTypeName(Method method)