通过getGenericSuperclass方法可以获取当前对象的直接超类的Type,使用该方法可以获取到泛型T的具体类型
package cn.tzz.lang.clazz; public class User { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class BaseHibernateDao<T,ID extends Serializable> { private Class<T> clazz; public BaseHibernateDao(){ //当前对象的直接超类的 Type Type genericSuperclass = getClass().getGenericSuperclass(); if(genericSuperclass instanceof ParameterizedType){ //参数化类型 ParameterizedType parameterizedType= (ParameterizedType) genericSuperclass; //返回表示此类型实际类型参数的 Type 对象的数组 Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); this.clazz= (Class<T>)actualTypeArguments[0]; }else{ this.clazz= (Class<T>)genericSuperclass; } } public Class<T> getClazz() { return clazz; } }
public class UserService extends BaseHibernateDao<User, Integer>{ }
测试实例:
public class TestUserService { public static void main(String[] args) { UserService userService = new UserService(); System.out.println(userService.getClass()); } }
运行结果:
class cn.tzz.lang.clazz.User