Ben
Ben

Reputation: 62454

How to call a method on a generic of a specific type

In the below Service I'm trying to init my Dao and inject the EntityManager into it. We're not using spring for this project. My IDE is complaining about calling setEntityManager() because it can't recognize that the object is always a GenericDao. Is this the proper way to do this?

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());
        }
    }
}

Upvotes: 1

Views: 62

Answers (1)

dcp
dcp

Reputation: 55468

You could use a cast:

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

But I think if you know it's always a GenericDao, why not just make it that type to begin with, e.g.

protected GenericDao dao;

And change the class declaration as well:

public class GenericService<T, GenericDao>

Upvotes: 2

Related Questions