有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HK2类型文字和通配符

我试着在HK2上使用球衣。我需要绑定非常奇怪的类型:

List<TransformationService<? extends Transformation, ? extends TransformationInfor>>

因此,我的活页夹定义如下:

resourceConfig.register(new AbstractBinder() {
        @Override
        protected void configure() {
            List<TransformationService<? extends Transformation, ? extends TransformationInfo>> transformationServices = ... ;

            bind(transformationServices)
                    .to(new TypeLiteral<List<TransformationService<? extends Transformation, ? extends TransformationInfo>>>() {});

            // This class needs the list for its construction
            bind(TransformationServiceImpl.class).to(TransformationService.class);
        }
    });

当我运行代码时,尽管我得到一个异常,我的列表不能被注入(包未被写入):

[11/20/15 16:46:34] WARNING org.glassfish.jersey.internal.Errors logErrors : The following warnings have been detected: WARNING: Unknown HK2 failure detected:
MultiException stack 1 of 3
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=List<TransformationService<? extends ...Transformation,? extends ...TransformationInfo>>,parent=TransformationServiceImpl,qualifiers={},position=3,optional=false,self=false,unqualified=null,334434299)
    at org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
    at org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:214)

有没有关于如何用HK2注入这种怪人的技巧


共 (1) 个答案

  1. # 1 楼答案

    据我所知,HK2注入规则与CDI相同(see spec

    在某一点上,它提到:

    However, some Java types are not legal bean types :

    • A type variable is not a legal bean type.
    • A parameterized type that contains a wildcard type parameter is not a legal bean type.
    • An array type whose component type is not a legal bean type.

    我认为在我的示例中,我试图创建TypeLiteral参数化类型,其中包含通配符

    无论如何,在我的例子中,我删除了那个无界类型,它就工作了。所需的改变是:

    bind(transformationServices)
        .to(new TypeLiteral<List<TransformationService>>() {});