Here you can find the source of getGenericType(Object target)
Parameter | Description |
---|---|
target | The target to get the generic class of |
T | The generic class type |
public static <T> Class<T> getGenericType(Object target)
//package com.java2s; /**/*from w w w . j a v a 2 s . com*/ * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ import java.lang.reflect.*; public class Main { /** * @param target The target to get the generic class of * @param <T> The generic class type * @return The generic class */ public static <T> Class<T> getGenericType(Object target) { return getGenericType(target, 0); } /** * @param target The target to get the generic class of * @param index The index the generic class is declared at * @param <T> The generic class type * @return The generic class */ public static <T> Class<T> getGenericType(Object target, int index) { Class<?> targetClass = target instanceof Class ? (Class<?>) target : target.getClass(); return getGenericType(targetClass, index); } private static <T> Class<T> getGenericType(Class<?> targetClass, int index) { // check targetClass first Type type = targetClass.getGenericSuperclass(); if (type instanceof ParameterizedType) { return extractGenericType((ParameterizedType) type, index); } if (type == null) { // targetClass is Object or primitive type return null; } // check implemented interfaces Type[] interfaceTypes = targetClass.getGenericInterfaces(); for (Type interfaceType : interfaceTypes) { if (interfaceType instanceof ParameterizedType) { return extractGenericType((ParameterizedType) interfaceType, index); } } // finally check the superclass return getGenericType(targetClass.getSuperclass(), index); } @SuppressWarnings("unchecked") private static <T> Class<T> extractGenericType(ParameterizedType parameterizedType, int index) { Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); Type actualTypeArgument = actualTypeArguments[index]; return (Class<T>) actualTypeArgument; } }