jsf-2glassfishcdi

Using @Inject with generic type


I've been searching here about it, but haven't found an answer.

In my application, I've an abstract main class for my controllers, with some methods and properties. And I want to inject the DAO automatically.

abstract class AbstractController<E extends AbstractEntity, D extends AbstractDAO<E>> {
    
    @Inject
    private D dao;

    // getters and setters
}

abstract class AbstractDAO<E extends AbstractEntity> {
    @PersistentContext
    private EntityManager em;

    // finds returns E
}

// implemenation/usage

class CarController extends AbstractController<Car, CarDAO> {
}

Getting the exception:

org.jboss.weld.exceptions.DefinitionException: WELD-001407 Cannot declare an injection point with a type variable: [field] @Inject private AbstractController.dao

Using: Glassfish 3.1 and JSF 2.1.

Is there a workaround or alternative for this?

Thanks.


Solution

  • It's technically very complicated for reflection to detect the proper runtime type by a generic declaration in the source and cast to it. Weld simply don't and won't support it.

    Better declare it against AbstractDAO<E>:

    private AbstractDAO<E> dao;
    

    You gain nothing with declaring it against D anyway.