1.public class EmployeeDAOImpl extends GenericDAOImpl<Employee>
2.public class GenericDAOImpl<T> implements IGenericDAO<T>
比如,从2中获取子类传过来的Employee,方法如下:在父类(GenericDAOImpl)中:
//获取子类中父类实现类的泛型参数(Employee/Department)
private Class<T> targetType;
public GenericDAOImpl(){
ParameterizedType pType = (ParameterizedType) this.getClass().getGenericSuperclass();
targetType = (Class<T>) pType.getActualTypeArguments()[0];
}
因为子类实例化会先调用父类构造方法,所以父类中this.getClass()是获得子类的字节码对象,再调用getGenericSuperclass();
获取父类中的带泛型的字节码,然后使用Type的子类调用getActualTypeArguments()
即可
还有一种LOW的方法,父类中:
public abstract Class<T> getTargetType();
子类覆盖返回 return XXXX.class即可;