Java Reflection Generic Type from Class getGenericType(Type type, Class rawType, int index)

Here you can find the source of getGenericType(Type type, Class rawType, int index)

Description

get Generic Type

License

Open Source License

Declaration

public static Class<?> getGenericType(Type type, Class<?> rawType, int index) 

Method Source Code

//package com.java2s;
/**//from w  w w .j  av a 2s.  co  m
 * Project: ocean.client.java.basic
 * 
 * File Created at 2011-10-27
 * $Id: GenericsUtil.java 311300 2013-12-23 06:15:28Z yichun.wangyc $
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */

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

public class Main {
    public static Class<?> getGenericType(Type type, Class<?> rawType, int index) {
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            if (rawType.equals(ptype.getRawType())) {
                Type[] typeArguments = ptype.getActualTypeArguments();
                if (index >= typeArguments.length || index < 0) {
                    throw new RuntimeException(
                            "index " + (index < 0 ? " must large then 0" : "out of arguments count"));
                }
                return getRawType(typeArguments[index]);
            }
        }
        return null;
    }

    public static Class<?>[] getGenericType(Type type) {
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            Type[] typeArguments = ptype.getActualTypeArguments();
            Class<?>[] types = new Class<?>[typeArguments.length];
            System.arraycopy(typeArguments, 0, types, 0, types.length);
            return types;
        }
        return null;
    }

    public static Class<?> getRawType(Type type) {
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            return getRawType(ptype.getRawType());
        } else if (type instanceof Class) {
            return (Class<?>) type;
        }
        return null;
    }
}

Related

  1. getGenericType(Class clazz, int index)
  2. getGenericType(Class target)
  3. getGenericType(Class type)
  4. getGenericType(Class type, Class clazz)
  5. getGenericType(Object o, Class declaringClass, int idx)
  6. getGenericTypeArgument(Class clazz, int index)
  7. getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class baseRequested)
  8. getGenericTypeArgumentsOfInheritedType(final Object object, final Class inheritedType)
  9. getGenericTypeClass(Class clazz, int index)