Java gets the type T.class of the 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;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325254815&siteId=291194637