Java gets the type t.class of generic t

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

public class Main{
    public static void main(String[] args)
    {
        Foo<String> foo = new Foo<String>(){};
        // 在类的外部这样获取
        Type type = ((ParameterizedType)foo.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        System.out.println(type);
        // 在类的内部这样获取
        System.out.println(foo.getTClass());
    }
}

abstract class Foo<T>{
    public Class<T> getTClass()
    {
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }
}

Output:

class java.lang.String
class java.lang.String

the above code is not omnipotent, only a subclass of instantiated T can get the actual type of T in the above method,
if the subclass does not instantiate T, you cannot get the actual type of T; For example, the class Child does not instantiate T, so it does not get string.class;

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

public class Main{
    public static void main(String[] args){
        //区别在new Child<String>()没有{}匿名类
        Foo<String> foo = new Child<String>();
        // 在类的外部这样获取
        Type type = ((ParameterizedType)foo.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        System.out.println(type);
        // 在类的内部这样获取
        System.out.println(foo.getTClass());
    }
}

abstract class Foo<T>{
    public Class<T> getTClass()
    {
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }
}

class Child<T> extends Foo<T>{
}

output:

Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    at com.hankcs.Main.main(Main.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

is a solution where the parent class itself does not get the concrete type of the generic type, but only provides abstract methods, and the subclass provides the concrete type

public abstract class Foo<T> {  
    public abstract Class getEntityClass();  
}  

public class Child extends Foo<String> {  
    public Class getEntityClass() {  
        return String.class;  
    }  
}  

the complete code for the method to get the generics is as follows :

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

public class GenericsUtils {
    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
     * GenricManager<Book>
     * 
     * @param clazz The class to introspect
     * @return the first generic declaration, or <code>Object.class</code> if cannot be determined
     */
    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
     * 
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     */
    public static Class getSuperClassGenricType(Class clazz, int index)
            throws IndexOutOfBoundsException {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }
}

reproduced source: http://blog.csdn.net/wangjunjun2008/article/details/43970217

http://www.hankcs.com/program/t-class.html
https://www.cnblogs.com/sirab415/p/6133533.html

Read More: