获取运行时带泛型父类的参数类型:
带泛型父类:
public class BaseDao<T> { private Class<T> entityClass;@SuppressWarnings("unchecked") public BaseDao() { Type superClass = this.getClass().getGenericSuperclass(); if (!(superClass instanceof ParameterizedType)) { return; } ParameterizedType pType = (ParameterizedType) superClass; Type[] types = pType.getActualTypeArguments(); if (types != null && types.length > 0) { entityClass = (Class<T>) types[0]; } }public Class<T> getEntityClass() { return entityClass; } } |
子类:
public class AccountDao1 extends BaseDao<Account> {public static void main(String[] args) { AccountDao1 accountDao1 = new AccountDao1(); Class class1 = accountDao1.getEntityClass(); System.out.println(class1.getName()); } } |
输出:
reflect.Account |
如果要获取本类中泛型的实例,需要在创建本类对象时同时初始化泛型的实际类型
例如:在有参构造器中将泛型作为参数传入。
public class AccountDao<T extends Account> { private Class<T> entityClass;public AccountDao(Class<T> entityClass) { super(); this.entityClass = entityClass; }public Class<T> getEntityClass1() { return entityClass; }public T getInstance() { if (entityClass != null) { try { return entityClass.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } } |