java - 如何实例化具有带参数的私有构造函数的泛型类
问题描述
我正在使用 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 。
如果该测试类来自某个库,则可能有创建它的方法......所以你可以避免使用反射。
推荐阅读
- c# - 执行时SQL代码显式转换错误
- python - 带有列表的高效正则表达式
- ios - 当任何事情发生时,一切都会暂时为零
- jquery - 物化css datepicker yearRange不工作
- android - 如何使用 volley 以新的意图解析 json 文件
- hyperledger-composer - 如何在使用 Mocha 进行测试时捕获交易
- python - 使用 os.walk 从 dir 及其子目录中获取所有文件
- sqlite - Android:从 SQLite 数据库填充 GridtView
- hibernate - 调用 setter 时发生 IllegalArgumentException
- java - 如何在java中更改二维数组中值的位置?