【问题标题】:How to call a method on a generic of a specific type如何在特定类型的泛型上调用方法
【发布时间】:2013-02-18 20:42:43
【问题描述】:

在下面的服务中,我试图初始化我的 Dao 并将 EntityManager 注入其中。我们没有在这个项目中使用 spring。我的 IDE 抱怨调用 setEntityManager(),因为它无法识别该对象始终是 GenericDao。这是正确的方法吗?

public class GenericService<T, Dao> {

    private static Logger logger = Logger.getLogger(Logger.class.getName());

    protected Dao dao;
    protected EntityManager em;

    public GenericService(Class<Dao> daoClass) {
        try {
            dao = daoClass.newInstance();

            EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
            em = emf.createEntityManager();

            dao.setEntityManager(em);

        } catch(InstantiationException e) {
            logger.log(Level.SEVERE, "Unable to initialize DAO: {1}", daoClass.getClass());
        } catch(IllegalAccessException e) {
            logger.log(Level.SEVERE, "Unable to initialize DAO: {1}", daoClass.getClass());
        }
    }
}

【问题讨论】:

    标签: java service dao


    【解决方案1】:

    你可以使用演员表:

    ((GenericDao)dao).setEntityManager(em);
    

    但我想如果你知道它总是一个 GenericDao,为什么不直接让它开始,例如

    protected GenericDao dao;
    

    同时更改类声明:

    public class GenericService<T, GenericDao>
    

    【讨论】:

    • 好电话...我需要的是public class GenericService&lt;T, Dao extends GenericDao&gt; {
    猜你喜欢
    • 2012-09-21
    • 2013-08-29
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多