Here you can find the source of getGenericParameterType(Class
Parameter | Description |
---|---|
T | type of class which it's generic parameter type needs to be founded. |
clazz | a parameter |
parameterIndex | index2 of generic parameter. start from 0. |
public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; public class Main { /**/*from w w w . j a v a 2 s . c o m*/ * note: for getting actual generic parameter, the object must be instantiated from an anonymouse * class (in line class overriding) * * @param <T> type of class which it's generic parameter type needs to be founded. * @param clazz * @param parameterIndex index2 of generic parameter. start from 0. * @return generic type class. if not found, return null; */ public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex) { Type type = clazz.getGenericSuperclass(); if (!(type instanceof ParameterizedType)) return null; ParameterizedType parameterizedType = ((ParameterizedType) clazz.getGenericSuperclass()); Type[] types = parameterizedType.getActualTypeArguments(); type = types[0]; while (type instanceof ParameterizedType) { types = ((ParameterizedType) type).getActualTypeArguments(); type = types[0]; } if (parameterIndex >= types.length) throw new RuntimeException("" + "parameter index2(" + parameterIndex + ") is bigger than or equal to" + " size of generic parameter lenght(" + types.length + ")."); Class beanClass = (Class) types[parameterIndex]; return beanClass; } public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex, Class defaultClass) { Class typeClass = getGenericParameterType(clazz, parameterIndex); return typeClass != null ? typeClass : defaultClass; } }