[英]Given a string as the type name of a generic class, how can I create the instance in runtime. If it is not possible, Is there another way?
[英]How can I create a new instance of a generic class
我創建一個這樣的功能
public <T extends ClientCoporate> void myFunction(List<T> clients){
T client = new T(); // issue
....
}
IDE錯誤Cannot instantiate the type T
一個簡單的問題,如何在這里擴展ClientCoporate
的任何類的新實例? 我嘗試搜索,但沒有希望,如果您能找到任何重復的問題,請隨時為我標記。 謝謝。
你不能
因為泛型在運行時被擦除,並且編譯器不知道要創建哪種類型的對象。 T
只是一個占位符,因此嘗試實例化它是非法的。
通常這個問題可以通過解決
public <T extends ClientCoporate> void myFunction(Class<T> clazz, List<T> clients){
T client = clazz.getDeclaredConstructor().newInstance(); ....
}
您不能執行此操作的原因之一-盡管可能至少還有幾個原因-是因為在您試圖構造T的那一刻,T的具體類型尚不明確。 我們不能肯定地說T的具體類型具有無參數構造函數。 我們唯一知道的是在ClientCoporate
有方法。
考慮以下類別:
class MyClientCoporate extends ClientCoporate // or implements, it doesn't matter
{
private MyClientCoporate() {}
}
我們不能在此類上使用new T()
,因為構造函數不是公共的。 這是編譯器不允許這樣做的原因之一。
如果您可以更改方法的簽名,則可以執行以下操作:
public <T extends ClientCoporate> void myFunction(List<T> clients, Supplier<T> constructor){
T client = constructor.get();
...
}
用法示例:
myFunction(aList, SomeClientCoporateClass::new);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.