繁体   English   中英

如何实例化具有带有参数的私有构造函数的泛型类

[英]How to instantiate generic class which has a private constructor with an argument

我正在使用3rd-party库创建Java应用程序,并希望实例化其类。 但是,该类是通用的,只有一个私有的构造函数。

我试图通过Guice注入创建一个实例。 Test<T>无法修改,因此我既没有使用@Inject进行注释,也没有添加非私有的零参数构造函数。

public class Test<T> {
    private final T value;

    private Test(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value.toString();
    }
}
Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
        bind(new TypeLiteral<Test<String>>() {
        });
    }
});
Test<String> test = (Test<String>) injector.getInstance(Test.class);
System.out.println(String.format("%s", test));
1) Could not find a suitable constructor in com.example.app.Test. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.

我想知道如何向Test类的构造函数添加参数,以及如何实例化它。

您可以(但可能不应该)使用反射来做到这一点:

    Constructor<Test> declaredConstructor = Test.class.getDeclaredConstructor(Object.class);
    declaredConstructor.setAccessible(true); // or if (declaredConstructor.trySetAccessible()) on java 9+
    Test<String> obj = declaredConstructor.newInstance("value of first parameter");

泛型在运行时会被忽略,因此您只需要在这里使用Object.class下限即可。 如果它将是class Test<T extends Something> ,则将查找Something.class ,否则默认为Object。

如果该测试类来自某个库,则可能有创建它的方法...因此可以避免使用反射。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM