泛型T的类型获取

T.getClass()或者T.class都是非法的,由于T是泛型变量。数组

因为一个类的类型是什么是在编译期处理的,故不能在运行时直接在Base里获得T的实际类型。函数

/** this

 * 能够在service层直接调用,也能够在DAO层扩展调用 spa

 */ 对象

public class BaseDaoImpl<T> implements BaseDao<T>接口

 

private Class<T> persistentClass;  get

/** io

* 用于Dao层子类使用的构造函数. 经过子类的泛型定义取得对象类型 编译

*/ class

public BaseDaoImpl(){  

    //getClass() 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的超类的 Class。  

    this.persistentClass=(Class<T>)getSuperClassGenricType(getClass(), 0);  

 

内部实现

/**
     * 经过反射, 得到定义Class时声明的父类的泛型参数的类型. 如没法找到, 返回Object.class.
     *
     *@param clazz
     *            clazz The class to introspect
     * @param index
     *            the Index of the generic ddeclaration,start from 0.
     * @return the index generic declaration, or Object.class if cannot be
     *         determined
     */
    public static Class<Object> getSuperClassGenricType(final Class clazz, final int index) {
     
     //返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
           return Object.class;
        }
        //返回表示此类型实际类型参数的 Type 对象的数组。
        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];    }

相关文章
相关标签/搜索