java class类型参数_使用Class对象实例化Java类型参数/ generic
如何實例化Java泛型對象,該對象僅接受類或參數給出的類型參數賓語?
例如:
通常,可以使用以下語法實例化Integer對象的ArrayList:
ArrayList foo = new ArrayList();
但是,給定一個Class諸如Integer.class之類的對象,怎么能創建一個類似的ArrayList?例如,我將如何做這樣的事情(語法不正確):
ArrayList foo = new ArrayList();
我需要這個用于Java的非常不尋常的事情(創建一個開源工具,用于可視化用戶提供的數據結構實例/他們編寫的泛型類).以下是我將如何使用此代碼的示例,該代碼說明了我將獲得的信息:
import java.util.ArrayList;
import java.util.List;
public class ArrayListFromClass {
// obviously this code does not work
public static void main(String[] args) {
Object givenObject = new Integer(4);
// I would not know it is Integer.class, a Class> object would be supplied by the user/ as a generic
Class> cls = givenObject.getClass();
List bar = new ArrayList();
// Where args[0] is "Integer.class"
List foo = new ArrayList();
// then I would be able to add to foo or bar with one or both of these techniques:
// printing givenObject.getClass() gives you java.lang.Integer, don't worry about the casting not working.
bar.add(cls.cast(givenObject));
Integer y = 6;
bar.add(y);
}
}
最佳答案 Java是靜態類型的.您希望實例化ArrayList的原因如下:
ArrayList foo = new ArrayList<>();
是讓你的IDE /編譯器知道,除了Integer以外的東西被放入列表中,顯示錯誤.除此之外,內部將忽略這種初始化,實際上甚至是erase the type.
所以,當你得到你的班級對象在運行時,您只知道代碼實際運行時類的類型.因此,IDE /編譯器無法在運行時警告您代碼中是否存在錯誤.
所以List< Object>在你的情況下會做得很好.如果你想要類型安全,你必須自己檢查,如下:
String sampleString = "String";
Class> clazz = sampleString.getClass();
...
if (clazz.isInstance(sampleString)) {
list.add(sampleString);
}
當你實際擁有一個Class時,.isInstance(Object obj)相當于instanceof.在眼前.
總結
以上是生活随笔為你收集整理的java class类型参数_使用Class对象实例化Java类型参数/ generic的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win11中initpki.dll加载失
- 下一篇: java美元兑换,(Java实现) 美元