Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it impossible to inject generic classes? [closed]

I have a generic abstract template class. I thought if I create type-specific Producers, I could inject some DAO service directly in the generic class. But I can't.

Why? And how could I work around this?

abstract class MyView<T> {
    @Inject
    MyDao<T> dao;

    //some more template methods that make use of the dao
    void someMethod() {
        dao.use();
    }
}

class CustomerView extends MyView<Customer> {
    //javax.enterprise.inject.AmbiguousResolutionException: Ambigious resolution
}


class DaoManager {
    @Produces
    MyDao<Customer> getDaoCustomer() {
        return DaoFactory.make(Customer.class);
    }

    @Produces
    MyDao<Product> getDaoProduct() {
        return DaoFactory.make(Product.class);
    }
}

When I inject eg a @Inject MyDao<Customer> dao; it works perfectly. But not with generics...

like image 932
membersound Avatar asked Oct 07 '13 21:10

membersound


People also ask

What are the restrictions on generics in Java programming?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

Can generic classes be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

How can we restrict generic to a subclass of particular class?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.


1 Answers

When you request

@Inject MyDao<Customer> dao;

the container knows that you want a bean specifically of type MyDao<Customer>. If such a bean exists and its type information is known, then the container can satisfy the injection. For example, the type information is preserved in your @Produces annotated method

@Produces
MyDao<Product> getDaoProduct() {

The container uses reflection to retrieve that parameterized type and can match it to the requested @Inject field.

With

abstract class MyView<T> {
    @Inject
    MyDao<T> dao;

however, all the container knows is that you want a MyDao. T is a type variable, not a concrete parameterization. The container cannot assume a specific type for it. In your case, both of the @Produces beans would match and there would be ambiguity.


In your example, we know from the context that it really wants a MyDao<Customer>. That doesn't seem to be something your container is capable of doing, ie. trying to resolve the type parameter to a concrete type argument for a parameterized subclass.

like image 187
Sotirios Delimanolis Avatar answered Nov 15 '22 14:11

Sotirios Delimanolis