简体   繁体   中英

How to pass enum as generic parameter

I'm implementing basic CRUD for REST service based on DAO injected via CDI. It's gonna work with multiple injections and I wanna pass the type of DAO from class that extends GenericRest . I followed this tutorial.

http://www.javacodegeeks.com/2013/06/java-ee-cdi-programmatic-dependency-disambiguation-example-injection-point-inspection.html

And get workable code:

GenericREST.java

public abstract class GenericREST {
    @Inject
    @DAOProducer
    @DAOType(DAO.COMMENT)
    private GenericDAO dao;
    ...
}

GenericDAO.java

public interface GenericDAO<T, PK extends Serializable> {
    public T create(T t);
    public T read(final PK id);
    public T update(T t);
    public void delete(final PK id);
}

It works well when I'm setting @DAOType as described above. But I wanna somehow select DAO by passing its' type from extended class.

Is there any way of doing it? Or maybe there is much easier way?

Assuming you use CDI instances, you can do something like this:

@Inject
@DAOProducer
private Instance<GenericDAO<?,?>> genericDaoInst;

protected GenericDAO<?,?> getDao(DAO dao) {
    return genericDaoInst.select(new DAOTypeLiteral(dao)).get();
}

then somewhere in your code...

GenericDAO<?,?> dao = getDao(DAO.COMMENT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM