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...
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.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With