Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用HK2在泛型类中注入类型参数_Java_Jersey_Hk2 - Fatal编程技术网

Java 使用HK2在泛型类中注入类型参数

Java 使用HK2在泛型类中注入类型参数,java,jersey,hk2,Java,Jersey,Hk2,我目前正在玩HK2 2.5.0-b05(这是Jersey 2.24使用的版本),我无法执行特定类型的注入。我能够概括我的问题,并提出了一个简单的小测试用例 代码如下: package com.github.fabriziocucci.test; import javax.inject.Inject; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.hk2.api.ServiceLocatorFactory;

我目前正在玩HK2 2.5.0-b05(这是Jersey 2.24使用的版本),我无法执行特定类型的注入。我能够概括我的问题,并提出了一个简单的小测试用例

代码如下:

package com.github.fabriziocucci.test;

import javax.inject.Inject;

import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.ServiceLocatorFactory;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.glassfish.hk2.utilities.binding.AbstractBinder;

public class Test {

    private static class A<T> {

        private final T t;

        @Inject
        public A(T t) {
            this.t = t;
            System.out.println(t);
        }

    }

    private static class B {

    }

    public static void main(String[] args) {
        ServiceLocator serviceLocator = ServiceLocatorFactory.getInstance().create(null);
        ServiceLocatorUtilities.bind(serviceLocator, new AbstractBinder() {
            @Override
            protected void configure() {
                bind(B.class).to(B.class);
                bindAsContract(new TypeLiteral<A<B>>() {}); // <--- ???
            }
        });

        serviceLocator.getService(new TypeLiteral<A<B>>() {}.getType());
    }

}
我肯定我的代码有问题,但我不知道是什么问题

更新1 我刚刚用hk2-2.5.0-b28做了同样的测试,除非我的代码包含一些细微的错误,否则结果是一样的


随后可能会有更多更新。

hk2的这一新功能现已随hk2-2.5.0-b29版本提供

您可以使用示例中的bindAsContract,但也可以直接在ActiveDescriptor上设置类型,或在EDSL中使用新的“asType”,如:

Type type = new TypeLiteral<A<B>>() {}.getType();

ActiveDescriptor<?> ad = BuilderHelper.activeLink(A.class).
            to(type).
            asType(type).build();
Type Type=new-TypeLiteral(){}.getType();
ActiveDescriptor ad=BuilderHelper.activeLink(A.class)。
到(类型)。
asType(type).build();

这现在不起作用,因为我们不支持设置自己参数化类型的对象。然而,我已经将您的测试添加到系统中,并且正在研究我们将来如何能够支持这一点!我刚试过,确实有效。我希望泽西岛能够很快接受这一变化。泽西岛刚刚接受了hk2版本2.5.0-b30,所以当泽西岛下一次发布一个新版本时,它将与具有此功能的hk2集成。好消息!我是否应该在GitHub上关闭该问题,并提及修复该问题的版本?
Type type = new TypeLiteral<A<B>>() {}.getType();

ActiveDescriptor<?> ad = BuilderHelper.activeLink(A.class).
            to(type).
            asType(type).build();