[英]How does default constructor used to instantiate object if it's super class no argument constructor has empty body?
[英]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.