栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

获取抽象超类上泛型类型参数的实际类型

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

获取抽象超类上泛型类型参数的实际类型

绝对有可能将其提取出来,

Class#getGenericSuperclass()
因为它不是在运行时定义的,而是在编译时由定义的
FooDaoextends baseDao<Foo>

这是一个启动示例,您可以如何在抽象类的构造函数中提取所需的泛型超类型,同时考虑子类的层次结构(以及

EntityManager
在无需显式提供类型的情况下将其应用于泛型方法的实际用例)):

public abstract class baseDao<E extends baseEntity> {    @PersistenceContext    private EntityManager em;    private Class<E> type;    @SuppressWarnings("unchecked") // For the cast on Class<E>.    public baseDao() {        Type type = getClass().getGenericSuperclass();        while (!(type instanceof ParameterizedType) || ((ParameterizedType) type).getRawType() != baseDao.class) { if (type instanceof ParameterizedType) {     type = ((Class<?>) ((ParameterizedType) type).getRawType()).getGenericSuperclass(); } else {     type = ((Class<?>) type).getGenericSuperclass(); }        }        this.type = (Class<E>) ((ParameterizedType) type).getActualTypeArguments()[0];    }    public E find(Long id) {        return em.find(type, id);    }    public List<E> list() {        return em.createQuery(String.format("SELECt e FROM %s e ORDER BY id", type.getSimpleName()), type).getResultList();    }    // ...}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485922.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号