为什么不能注入泛型类

为什么不能注入泛型类

本文介绍了为什么不能注入泛型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的抽象模板类。我想如果我创建特定于类型的生成器,我可以直接在泛型类中注入一些DAO服务。但我不能。

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

当我注入例如 @Inject MyDao< Customer> dao; 它完美无缺。但不是用泛型...

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

推荐答案

当你要求时

@Inject MyDao<Customer> dao;

容器知道你想要一个特定类型的bean MyDao< Customer> 。如果存在这样的bean并且其类型信息是已知的,则容器可以满足注入。例如,类型信息保存在 @Produces 带注释的方法中

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() {

容器使用反射来检索参数化类型,并且可以将其与请求的 @Inject 字段。

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

使用

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

然而,所有容器都知道你想要一个 MyDao T 是一个类型变量,而不是具体的参数化。容器不能为其采用特定类型。在您的情况下,两个 @Produces bean都匹配,并且会有歧义。

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.

在您的示例中,我们从上下文中知道它确实需要 MyDao< Customer> 。这似乎不是你的容器能做的事情,即。尝试将类型参数解析为参数化子类的具体类型参数。

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.

这篇关于为什么不能注入泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:18