gpt4 book ai didi

java - 如何实例化具有带参数的私有(private)构造函数的泛型类

转载 作者:行者123 更新时间:2023-12-02 01:00:44 25 4
gpt4 key购买 nike

我正在使用第 3 方库创建一个 java 应用程序,并且想要实例化它的类。但是,该类是通用的,并且只有一个私有(private)构造函数。

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

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但除此之外它默认是对象。

如果该测试类来自某个库,也许有创建它的方法......这样您就可以避免使用反射。

关于java - 如何实例化具有带参数的私有(private)构造函数的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57771197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com