运行时获取泛型T

在编译期间T被搞成Object,类型丢失,所以是不能直接取到的.但有时可以变通地取到,比如:  

public class GenericType<T> { 
    protected GenericType() { 
        Type superclass = getClass().getGenericSuperclass(); 
        if (!(superclass instanceof ParameterizedType)) { 
            throw new RuntimeException("Missing type parameter."); 
        } 
        ParameterizedType parameterized = (ParameterizedType) superclass; 
        
        Class<T> messageType = parameterized.getActualTypeArguments()[0]; 
    } 

一般人俺不告诉他

 

 

public <T> Object executeQuery(MybatisCallBack<T> callback){ 
Class<MybatisCallBack> clazz=callback.getClass();
//下面就是用楼上方式取这个class的泛型了
Type superclass = clazz.getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType)) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        
        Class<T> messageType = parameterized.getActualTypeArguments()[0];

}
 

你可能感兴趣的:(泛型)