范型父类获取子类类型

网上给出的答案大多是:

protected Class<T> getModelName() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType p = (ParameterizedType) t ;
		Class<T> c = (Class<T>) p.getActualTypeArguments()[0];
		return c;
}

但是遇到Cglib代理会继续继承子类,需要判断并继续取父类,并获取泛型:

// 父类
public abstract class BaseClass<T>{
    protected Class<T> getModelName() {
        Type t = getClass().getGenericSuperclass();
        // Cglib代理可能会继承子类,需要取父类名称
        if(!(t instanceof ParameterizedType)){
            t = getClass().getSuperclass().getGenericSuperclass();
        }
        ParameterizedType p = (ParameterizedType) t ;
        Class<T> c = (Class<T>) p.getActualTypeArguments()[0];
        return c;
    }
		
    ...
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容